Condividi tramite


EXISTS (Transact-SQL)

Specifica una sottoquery per testare l'esistenza di righe.

Icona di collegamento a un argomento Convenzioni della sintassi Transact-SQL

Sintassi

EXISTS subquery

Argomenti

  • subquery
    Istruzione SELECT con restrizioni. La parola chiave INTO non è consentita. Per ulteriori informazioni, vedere la descrizione delle sottoquery in SELECT (Transact-SQL).

Tipi di risultati

Boolean

Valori dei risultati

Restituisce TRUE se una sottoquery include una o più righe.

Esempi

A.Utilizzo di NULL in una sottoquery per restituire sempre un set di risultati

Nell'esempio seguente viene restituito un set di risultati grazie all'aggiunta di NULL nella sottoquery e viene comunque restituito TRUE tramite l'utilizzo della parola chiave EXISTS.

USE AdventureWorks2012 ;
GO
SELECT DepartmentID, Name 
FROM HumanResources.Department 
WHERE EXISTS (SELECT NULL)
ORDER BY Name ASC ;

B.Confronto di query con le parole chiave EXISTS e IN

Nell'esempio seguente vengono confrontate due query equivalenti da un punto di vista semantico. Nella prima query viene utilizzata la parola chiave EXISTS, mentre nella seconda query viene utilizzata la parola chiave IN.

USE AdventureWorks2012 ;
GO
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

Nella query seguente viene utilizzata la parola chiave IN.

USE AdventureWorks2012 ;
GO
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

Di seguito è riportato il set di risultati per entrambe le query.

FirstName LastName

-------------------------------------------------- ----------

Barry Johnson

David Johnson

Willis Johnson

(3 row(s) affected)

C.Confronto di query con le parole chiave EXISTS e = ANY

Nell'esempio seguente vengono illustrate due query per la ricerca di negozi il cui nome coincide con quello del fornitore. Nella prima query viene utilizzata la parola chiave EXISTS, mentre nella seconda query viene utilizzata la parola chiave = ANY.

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

Nella query seguente viene utilizzata la parola chiave = ANY.

USE AdventureWorks2012 ;
GO
SELECT DISTINCT s.Name
FROM Sales.Store AS s 
WHERE s.Name = ANY
(SELECT v.Name
    FROM Purchasing.Vendor AS v ) ;
GO

D.Confronto di query con le parole chiave EXISTS e IN

Nell'esempio seguente vengono illustrate query per la ricerca di dipendenti facenti parte di reparti il cui nome inizia con la lettera P.

USE AdventureWorks2012;
GO
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

Nella query seguente viene utilizzata la parola chiave IN.

USE AdventureWorks2012;
GO
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.Utilizzo della parola chiave NOT EXISTS

La parola chiave NOT EXISTS funziona in modo inverso rispetto a EXISTS. La clausola WHERE in NOT EXISTS viene soddisfatta se la sottoquery non restituisce alcuna riga. Nell'esempio seguente vengono cercati i dipendenti che non fanno parte di reparti il cui nome inizia con la lettera 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

Set di risultati:

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)

Vedere anche

Riferimento

Espressioni (Transact-SQL)

Funzioni predefinite (Transact-SQL)

WHERE (Transact-SQL)