Set Variable value in exists condition sql server

Vishal Sharma picture Vishal Sharma · Mar 11, 2014 · Viewed 91.8k times · Source
 Declare @CategoryID as int
BEGIN  
    SELECT 
    (CASE 
        WHEN EXISTS(
            SELECT t0.Categoryid AS [EMPTY]
            FROM Categories AS [t0]
            WHERE [t0].Categoryname = @CategoryName
           ) THEN 1
        ELSE 0
     END) AS [value]

if i want to set my variable inside exists block with t0.Categoryid how could i do that ?

what i want is to replace then 1 to the category id value...

thanks in advance..

Answer

M.Ali picture M.Ali · Mar 11, 2014
Declare @CategoryID as int
SET @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;
 END
ELSE
 BEGIN
   SET @CategoryID = 0;
 END