Set Variable value in exists condition sql server Set Variable value in exists condition sql server sql sql

Set Variable value in exists condition sql server


Declare @CategoryID as intSET @CategoryID =  CASE WHEN EXISTS(SELECT 1                                    FROM  Categories                                    WHERE Categoryname = @CategoryName)                     THEN 1 ELSE 0                   END

Another way would be something like ....

IF EXISTS (SELECT 1           FROM  Categories           WHERE Categoryname = @CategoryName) BEGIN   SET @CategoryID = 1; ENDELSE BEGIN   SET @CategoryID = 0; END


My 2 cents...

DECLARE @any BIT = 0SELECT TOP 1 @any = 1 FROM Categories WHERE CategoryName = @CategoryNameIF (@any = 1)  PRINT 'Yes'ELSE  PRINT 'No'


This will return the category id, if it exists, and 0 if it does not.

SET @CategoryID = null;SELECT @CategoryID = t0.CategoryidFROM Categories AS [t0]WHERE [t0].Categoryname = @CategoryName;IF @CategoryID IS NULL    SET @CategoryID = 0;SELECT @CategoryID AS [value];

However, I would recommend just returning null if it doesn't exist, or returning an additional @Exists (BIT) to indicate if it exists or not.