SQL Server根据具体情况选择

时间:2016-06-07 04:39:32

标签: sql-server

我想排除只有至少有一条记录具有值的UserID为NULL的记录。

IF EXISTS (SELECT * FROM @MySavedSearches WHERE UserID IS NOT NULL)
    SELECT SSM.* 
    FROM XYZTABLE SSM
    JOIN @MySavedSearches MySearches ON SSM.UniqueID = MySearches.UniqueID AND MySearches.UserID IS NOT NULL
ELSE
    SELECT SSM.* 
    FROM XYZTABLE  SSM
    JOIN @MySavedSearches MySearches ON SSM.UniqueID = MySearches.UniqueID

通过上述查询,我​​能够得到理想的结果,但不知怎的,我觉得这不是正确的方法。

1 个答案:

答案 0 :(得分:2)

获取变量的计数并检查where:

DECLARE @cnt int
SELECT @cnt = count(*) FROM @MySavedSearches WHERE UserID IS NOT NULL

SELECT SSM.* 
    FROM XYZTABLE SSM
    JOIN @MySavedSearches MySearches ON SSM.UniqueID = MySearches.UniqueID 
             AND ((@cnt > 0 AND MySearches.UserID IS NOT NULL) OR (@cnt = 0))