If Exist or Exists?

user1142433 picture user1142433 · Jan 11, 2013 · Viewed 14.9k times · Source

Is it possible to test two EXISTS conditions in a single IF SQL statement? I've tried the following.

IF EXIST (SELECT * FROM tblOne WHERE field1 = @parm1 AND field2 = @parm2) 
   OR 
   EXIST (SELECT * FROM tblTwo WHERE field1 = @parm5 AND field2 = @parm3) 

I've tried playing with adding additional IF and parenthesis in there, but to no avail.

Can you help me out with the proper syntax?

Answer

Martin Smith picture Martin Smith · Jan 11, 2013

If SQL Server

IF EXISTS (SELECT *
           FROM   tblOne
           WHERE  field1 = @parm1
                  AND field2 = @parm2)
    OR EXISTS (SELECT *
               FROM   tblTwo
               WHERE  field1 = @parm5
                      AND field2 = @parm3)
  PRINT 'YES' 

Is fine, note the only thing changed is EXISTS not EXIST. The plan for this will probably be a UNION ALL that short circuits if the first one tested is true.