TSQL条件IS NULL和=运算符

时间:2010-12-15 15:41:38

标签: tsql

我试图在一个声明中写这个,怎么做?

-- Is there a block for this user?
SELECT @BlockID = BlockID FROM [Blocks]  
WHERE UserID = @UserID

-- If not exists, get the default one
IF @BlockID IS NULL  
SELECT @BlockID = BlockID FROM [Blocks]  
WHERE UserID IS NULL

3 个答案:

答案 0 :(得分:2)

SET @BlockID = (SELECT TOP 1 BlockID
                FROM [Blocks]
                WHERE UserID IS NULL OR UserID = @UserID
                ORDER BY CASE WHEN UserID IS NOT NULL THEN 0 ELSE 1 END)

答案 1 :(得分:1)

coalesce。它也很容易扩展到两个以上。

select
  @BlockID = coalesce(u.BlockID, d.BlockID)
from
  Blocks d
  left join Blocks u on u.UserID = @UserID
where
  d.UserID is null

答案 2 :(得分:-1)

SET @BlockID = (SELECT BlockID FROM [Blocks] WHERE UserID IS NULL)