如果不满足条件,则获取包括NULL在内的所有值

问题描述:

要么仅获取具有指定@Lastname的那些用户ID,要么如果@LastName ='All',则即使它们的姓氏为NULL,也获取所有用户ID.

Either get only those userIDs with the specified @Lastname or if @LastName = 'All' then get all userIDs even if they have NULL values as their LastName.

SELECT userID INTO #table 
FROM users 
WHERE LastName = CASE 
                 WHEN @LastName = 'All' THEN LastName 
                 ELSE @LastName END

上面的查询仅返回LastName不为NULL的那些用户ID.

The above query only returns those userIDs where the LastName is not NULL.

另一个简短形式

where @LastName in ('All', LastName);

SqlFiddle