EXISTS (Transact-SQL)EXISTS (Transact-SQL)

ОБЛАСТЬ ПРИМЕНЕНИЯ:даSQL Server (начиная с 2008)даБаза данных SQL AzureдаХранилище данных SQL AzureдаParallel Data WarehouseAPPLIES TO: yesSQL Server (starting with 2008) yesAzure SQL Database yesAzure SQL Data Warehouse yesParallel Data Warehouse

Указывает вложенный запрос для проверки существования строк.Specifies a subquery to test for the existence of rows.

Значок ссылки на раздел Синтаксические обозначения в Transact-SQLTopic link icon Transact-SQL Syntax Conventions

СинтаксисSyntax

EXISTS ( subquery )  

АргументыArguments

subquerysubquery
Ограниченная инструкция SELECT.Is a restricted SELECT statement. Ключевое слово INTO не допускается.The INTO keyword is not allowed. Дополнительные сведения о вложенных запросах см. в разделе SELECT (Transact-SQL).For more information, see the information about subqueries in SELECT (Transact-SQL).

Типы результатаResult Types

BooleanBoolean

Результирующие значенияResult Values

Возвращает значение TRUE, если вложенный запрос содержит хотя бы одну строку.Returns TRUE if a subquery contains any rows.

ПримерыExamples

A.A. Использование значения NULL во вложенном запросе для возвращения результирующего набораUsing NULL in a subquery to still return a result set

В следующем примере возвращается результирующий набор со значением NULL, указанным во вложенном запросе, и устанавливается значение TRUE с помощью ключевого слова EXISTS.The following example returns a result set with NULL specified in the subquery and still evaluates to TRUE by using EXISTS.

-- Uses AdventureWorks  
  
SELECT DepartmentID, Name   
FROM HumanResources.Department   
WHERE EXISTS (SELECT NULL)  
ORDER BY Name ASC ;  

Б.B. Сравнение запросов с помощью ключевых слов EXISTS и INComparing queries by using EXISTS and IN

В следующем примере сравниваются два семантически эквивалентных запроса.The following example compares two queries that are semantically equivalent. В первом запросе используется ключевое слово EXISTS, а во втором — ключевое слово IN.The first query uses EXISTS and the second query uses IN.

-- Uses AdventureWorks  
  
SELECT a.FirstName, a.LastName  
FROM Person.Person AS a  
WHERE EXISTS  
(SELECT *   
    FROM HumanResources.Employee AS b  
    WHERE a.BusinessEntityID = b.BusinessEntityID  
    AND a.LastName = 'Johnson');  
GO  

В следующем запросе используется ключевое слово IN.The following query uses IN.

-- Uses AdventureWorks  
  
SELECT a.FirstName, a.LastName  
FROM Person.Person AS a  
WHERE a.LastName IN  
(SELECT a.LastName  
    FROM HumanResources.Employee AS b  
    WHERE a.BusinessEntityID = b.BusinessEntityID  
    AND a.LastName = 'Johnson');  
GO  

Здесь приведен результирующий набор для каждого запроса.Here is the result set for either query.

FirstName                                          LastName
-------------------------------------------------- ----------
Barry                                              Johnson
David                                              Johnson
Willis                                             Johnson
 
(3 row(s) affected)

В.C. Сравнение запросов с помощью ключевых слов EXISTS и = ANYComparing queries by using EXISTS and = ANY

В следующем примере показаны два запроса для поиска магазинов, названия которых совпадают с названием поставщика.The following example shows two queries to find stores whose name is the same name as a vendor. В первом запросе используется ключевое слово EXISTS, а во втором — ключевое слово =``ANY.The first query uses EXISTS and the second uses =``ANY.

-- Uses AdventureWorks  
  
SELECT DISTINCT s.Name  
FROM Sales.Store AS s   
WHERE EXISTS  
(SELECT *  
    FROM Purchasing.Vendor AS v  
    WHERE s.Name = v.Name) ;  
GO  

В следующем запросе используется ключевое слово = ANY.The following query uses = ANY.

-- Uses AdventureWorks  
  
SELECT DISTINCT s.Name  
FROM Sales.Store AS s   
WHERE s.Name = ANY  
(SELECT v.Name  
    FROM Purchasing.Vendor AS v ) ;  
GO  

Г.D. Сравнение запросов с помощью ключевых слов EXISTS и INComparing queries by using EXISTS and IN

В следующем примере показаны запросы для поиска сотрудников подразделений, имена которых начинаются на P.The following example shows queries to find employees of departments that start with P.

-- Uses AdventureWorks  
  
SELECT p.FirstName, p.LastName, e.JobTitle  
FROM Person.Person AS p   
JOIN HumanResources.Employee AS e  
   ON e.BusinessEntityID = p.BusinessEntityID   
WHERE EXISTS  
(SELECT *  
    FROM HumanResources.Department AS d  
    JOIN HumanResources.EmployeeDepartmentHistory AS edh  
       ON d.DepartmentID = edh.DepartmentID  
    WHERE e.BusinessEntityID = edh.BusinessEntityID  
    AND d.Name LIKE 'P%');  
GO  

В следующем запросе используется ключевое слово IN.The following query uses IN.

-- Uses AdventureWorks  
  
SELECT p.FirstName, p.LastName, e.JobTitle  
FROM Person.Person AS p JOIN HumanResources.Employee AS e  
   ON e.BusinessEntityID = p.BusinessEntityID   
JOIN HumanResources.EmployeeDepartmentHistory AS edh  
   ON e.BusinessEntityID = edh.BusinessEntityID   
WHERE edh.DepartmentID IN  
(SELECT DepartmentID  
   FROM HumanResources.Department  
   WHERE Name LIKE 'P%');  
GO  

Д.E. Использование ключевого слова NOT EXISTSUsing NOT EXISTS

Работа ключевого слова NOT EXISTS противоположна работе ключевого слова EXISTS.NOT EXISTS works the opposite of EXISTS. Предложение WHERE в ключевом слове NOT EXISTS удовлетворяется, если вложенный запрос не возвратил никаких строк.The WHERE clause in NOT EXISTS is satisfied if no rows are returned by the subquery. В следующем примере выполняется поиск сотрудников, не входящих в состав подразделений, имена которых начинаются на P.The following example finds employees who are not in departments which have names that start with P.

SELECT p.FirstName, p.LastName, e.JobTitle  
FROM Person.Person AS p   
JOIN HumanResources.Employee AS e  
   ON e.BusinessEntityID = p.BusinessEntityID   
WHERE NOT EXISTS  
(SELECT *  
   FROM HumanResources.Department AS d  
   JOIN HumanResources.EmployeeDepartmentHistory AS edh  
      ON d.DepartmentID = edh.DepartmentID  
   WHERE e.BusinessEntityID = edh.BusinessEntityID  
   AND d.Name LIKE 'P%')  
ORDER BY LastName, FirstName  
GO  

Ниже приводится результирующий набор.Here is the result set.

FirstName                      LastName                       Title
------------------------------ ------------------------------ ------------
Syed                           Abbas                          Pacific Sales Manager
Hazem                          Abolrous                       Quality Assurance Manager
Humberto                       Acevedo                        Application Specialist
Pilar                          Ackerman                       Shipping & Receiving Superviso
François                       Ajenstat                       Database Administrator
Amy                            Alberts                        European Sales Manager
Sean                           Alexander                      Quality Assurance Technician
Pamela                         Ansman-Wolfe                   Sales Representative
Zainal                         Arifin                         Document Control Manager
David                          Barber                         Assistant to CFO
Paula                          Barreto de Mattos              Human Resources Manager
Shai                           Bassli                         Facilities Manager
Wanida                         Benshoof                       Marketing Assistant
Karen                          Berg                           Application Specialist
Karen                          Berge                          Document Control Assistant
Andreas                        Berglund                       Quality Assurance Technician
Matthias                       Berndt                         Shipping & Receiving Clerk
Jo                             Berry                          Janitor
Jimmy                          Bischoff                       Stocker
Michael                        Blythe                         Sales Representative
David                          Bradley                        Marketing Manager
Kevin                          Brown                          Marketing Assistant
David                          Campbell                       Sales Representative
Jason                          Carlson                        Information Services Manager
Fernando                       Caro                           Sales Representative
Sean                           Chai                           Document Control Assistant
Sootha                         Charncherngkha                 Quality Assurance Technician
Hao                            Chen                           HR Administrative Assistant
Kevin                          Chrisulis                      Network Administrator
Pat                            Coleman                        Janitor
Stephanie                      Conroy                         Network Manager
Debra                          Core                           Application Specialist
Ovidiu                         Crãcium                        Sr. Tool Designer
Grant                          Culbertson                     HR Administrative Assistant
Mary                           Dempsey                        Marketing Assistant
Thierry                        D'Hers                         Tool Designer
Terri                          Duffy                          VP Engineering
Susan                          Eaton                          Stocker
Terry                          Eminhizer                      Marketing Specialist
Gail                           Erickson                       Design Engineer
Janice                         Galvin                         Tool Designer
Mary                           Gibson                         Marketing Specialist
Jossef                         Goldberg                       Design Engineer
Sariya                         Harnpadoungsataya              Marketing Specialist
Mark                           Harrington                     Quality Assurance Technician
Magnus                         Hedlund                        Facilities Assistant
Shu                            Ito                            Sales Representative
Stephen                        Jiang                          North American Sales Manager
Willis                         Johnson                        Recruiter
Brannon                        Jones                          Finance Manager
Tengiz                         Kharatishvili                  Control Specialist
Christian                      Kleinerman                     Maintenance Supervisor
Vamsi                          Kuppa                          Shipping & Receiving Clerk
David                          Liu                            Accounts Manager
Vidur                          Luthra                         Recruiter
Stuart                         Macrae                         Janitor
Diane                          Margheim                       Research & Development Enginee
Mindy                          Martin                         Benefits Specialist
Gigi                           Matthew                        Research & Development Enginee
Tete                           Mensa-Annan                    Sales Representative
Ramesh                         Meyyappan                      Application Specialist
Dylan                          Miller                         Research & Development Manager
Linda                          Mitchell                       Sales Representative
Barbara                        Moreland                       Accountant
Laura                          Norman                         Chief Financial Officer
Chris                          Norred                         Control Specialist
Jae                            Pak                            Sales Representative
Wanda                          Parks                          Janitor
Deborah                        Poe                            Accounts Receivable Specialist
Kim                            Ralls                          Stocker
Tsvi                           Reiter                         Sales Representative
Sharon                         Salavaria                      Design Engineer
Ken                            Sanchez                        Chief Executive Officer
José                           Saraiva                        Sales Representative
Mike                           Seamans                        Accountant
Ashvini                        Sharma                         Network Administrator
Janet                          Sheperdigian                   Accounts Payable Specialist
Candy                          Spoon                          Accounts Receivable Specialist
Michael                        Sullivan                       Sr. Design Engineer
Dragan                         Tomic                          Accounts Payable Specialist
Lynn                           Tsoflias                       Sales Representative
Rachel                         Valdez                         Sales Representative
Garrett                        Vargar                         Sales Representative
Ranjit                         Varkey Chudukatil              Sales Representative
Bryan                          Walton                         Accounts Receivable Specialist
Jian Shuo                      Wang                           Engineering Manager
Brian                          Welcker                        VP Sales
Jill                           Williams                       Marketing Specialist
Dan                            Wilson                         Database Administrator
John                           Wood                           Marketing Specialist
Peng                           Wu                             Quality Assurance Supervisor
 
(91 row(s) affected)

Примеры: Хранилище данных SQL AzureAzure SQL Data Warehouse и Параллельное хранилище данныхParallel Data WarehouseExamples: Хранилище данных SQL AzureAzure SQL Data Warehouse and Параллельное хранилище данныхParallel Data Warehouse

Е.F. Использование ключевого слова EXISTSUsing EXISTS

В следующем примере определяется, могут ли строки в таблице ProspectiveBuyer соответствовать строкам в таблице DimCustomer.The following example identifies whether any rows in the ProspectiveBuyer table could be matches to rows in the DimCustomer table. Запрос будет возвращать строки, только при совпадении значений LastName и BirthDate в двух таблицах.The query will return rows only when both the LastName and BirthDate values in the two tables match.

-- Uses AdventureWorks  
  
SELECT a.LastName, a.BirthDate  
FROM DimCustomer AS a  
WHERE EXISTS  
(SELECT *   
    FROM dbo.ProspectiveBuyer AS b  
    WHERE (a.LastName = b.LastName) AND (a.BirthDate = b.BirthDate));  

Ж.G. Использование ключевого слова NOT EXISTSUsing NOT EXISTS

Работа ключевого слова NOT EXISTS противоположна работе ключевого слова EXISTS.NOT EXISTS works as the opposite as EXISTS. Предложение WHERE в ключевом слове NOT EXISTS удовлетворяется, если вложенный запрос не возвратил никаких строк.The WHERE clause in NOT EXISTS is satisfied if no rows are returned by the subquery. В следующем примере показан поиск всех строк в таблице DimCustomer, где LastName и BirthDate не соответствуют записям в таблице ProspectiveBuyers.The following example finds rows in the DimCustomer table where the LastName and BirthDate do not match any entries in the ProspectiveBuyers table.

-- Uses AdventureWorks  
  
SELECT a.LastName, a.BirthDate  
FROM DimCustomer AS a  
WHERE NOT EXISTS  
(SELECT *   
    FROM dbo.ProspectiveBuyer AS b  
    WHERE (a.LastName = b.LastName) AND (a.BirthDate = b.BirthDate));  

См. такжеSee Also

Выражения (Transact-SQL) Expressions (Transact-SQL)
Встроенные функции (Transact-SQL) Built-in Functions (Transact-SQL)
WHERE (Transact-SQL)WHERE (Transact-SQL)