我想排除只有至少有一条记录具有值的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
通过上述查询,我能够得到理想的结果,但不知怎的,我觉得这不是正确的方法。
答案 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))