tRuEsAtM
tRuEsAtM

Reputation: 3668

Updating the SQL query from Count(*) to EXISTS in SQL Server

I have the following SQL query,

CASE 
    WHEN (SELECT COUNT(*) 
        FROM MyTable AS Parameter
                    INNER JOIN Table ON Parameter.Attribute1 = Table.Attribute2
                    WHERE FD.DefID= Parameter.DefID AND Parameter.VTypeID = 1) = 0
    THEN (
SELECT * from Table2)
ELSE
    NULL
END AS Items

Basically, I would like to ensure that conditional execution is only if the query result count is 0. How should I modify it to use EXISTS/NOT EXISTS keyword?

Upvotes: 0

Views: 139

Answers (1)

Slavian Petrov
Slavian Petrov

Reputation: 652

You can use exists to do that like so:

SELECT * from Table2
WHERE NOT EXISTS(
    SELECT 1
    FROM MyTable AS Parameter
    INNER JOIN Table ON Parameter.Attribute1 = Table.Attribute2
    WHERE FD.DefID= Parameter.DefID AND Parameter.VTypeID = 1)

Upvotes: 2

Related Questions