寻找一种优雅的解决方法......
DECLARE @ZIP INT
SET @ZIP = 55555
IF @ZIP = ALL(SELECT ZIP FROM PEOPLE WHERE PERSONTYPE = 1)
PRINT 'All people of type 1 have the same zip!'
ELSE
PRINT 'Not All people of type 1 have the same zip!'
问题是,如果(SELECT ZIP FROM PEOPLE WHERE PERSONTYPE = 1)没有返回记录,那么上面的IF计算结果为true。我正在寻找一种方法,当ALL的子查询没有返回任何记录时,将其评估为false。
我目前的解决方案:
DECLARE @ZIP INT
SET @ZIP = 55555
DECLARE @ALLZIPS TABLE (INT ZIP)
INSERT INTO @ALLZIPS
SELECT ZIP FROM PEOPLE WHERE PERSONTYPE = 1
IF EXISTS(SELECT TOP 1 * FROM @ALLZIPS) AND (@ZIP = ALL (SELECT ZIP FROM @ALLZIPS))
PRINT 'All people of type 1 have the same zip!'
ELSE
PRINT 'Not All people of type 1 have the same zip!'
答案 0 :(得分:3)
使用:
IF EXISTS(SELECT NULL
FROM PEOPLE p
WHERE p.persontype = 1
HAVING MIN(p.zip) = @Zip
AND MAX(p.zip) = @Zip)
PRINT 'All people of type 1 have the same zip!'
ELSE
PRINT 'Not All people of type 1 have the same zip!'
答案 1 :(得分:2)
考虑使用EXISTS。
IF @ZIP = ALL(SELECT ZIP FROM PEOPLE WHERE PERSONTYPE = 1)
AND EXISTS(SELECT 1 FROM PEOPLE WHERE PERSONTYPE = 1)
答案 2 :(得分:2)
跳进去:
IF (SELECT SUM(CASE WHEN ZIP = @ZIP THEN 0 ELSE 1 END)
FROM PEOPLE WHERE PERSONTYPE = 1) = 0
PRINT 'All people of type 1 have the same zip!'
ELSE
PRINT 'Not All people of type 1 have the same zip!'