在存在条件sql server中设置变量值

时间:2014-03-11 09:40:00

标签: sql sql-server sql-server-2008 exists

 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]

如果我想用t0.Categoryid在变量内设置我的变量怎么能这样做呢?

我想要的是将然后1 替换为类别ID值...

提前感谢..

6 个答案:

答案 0 :(得分:26)

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

另一种方式就是......

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

答案 1 :(得分:5)

这将返回类别ID(如果存在),如果不存在则返回0。

SET @CategoryID = null;

SELECT @CategoryID = t0.Categoryid
FROM Categories AS [t0]
WHERE [t0].Categoryname = @CategoryName;

IF @CategoryID IS NULL
    SET @CategoryID = 0;

SELECT @CategoryID AS [value];

但是,如果不存在,我建议只返回null,或者返回一个额外的@Exists(BIT)来指示它是否存在。

答案 2 :(得分:3)

我的2美分......

DECLARE @any BIT = 0
SELECT TOP 1 @any = 1 FROM Categories WHERE CategoryName = @CategoryName

IF (@any = 1)
  PRINT 'Yes'
ELSE
  PRINT 'No'

答案 3 :(得分:1)

哟可以这样试试。

Declare @CategoryID as int
 Set @CategoryID =0;
    SELECT @CategoryID=t0.Categoryid
    FROM Categories AS [t0]
    WHERE [t0].Categoryname = @CategoryName

IF类别名称存在而不是指定该类别的类别ID,否则保持为零。

答案 4 :(得分:1)

Declare @CategoryID as int
SET @CategoryID =
            (SELECT t0.Categoryid AS [EMPTY]
            FROM Categories AS [t0]
            WHERE [t0].Categoryname = @CategoryName)
SET @CategoryID =COALESCE(@CategoryID ,0)

答案 5 :(得分:0)

您可以在几行中使用这种方法

DECLARE @CategoryID int
SELECT @CategoryID = Categoryid FROM Categories WHERE Categoryname = @CategoryName

IF @CategoryID IS NULL
    THROW 50000, N'not found', 1 -- do something
    
SELECT @CategoryID -- the Categoryid value