views:

71

answers:

3

Looking for an elegant way to workaround this...

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!'

The issue is that, if (SELECT ZIP FROM PEOPLE WHERE PERSONTYPE = 1) returns no records, then the above IF evaluates to true. I'm looking for a way to make this evaluate to false when there are no records returned by the ALL's subquery.

My current solution:

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!'
+2  A: 

Consider using EXISTS as well.

IF @ZIP = ALL(SELECT ZIP FROM PEOPLE WHERE PERSONTYPE = 1)  
   AND EXISTS(SELECT 1 FROM PEOPLE WHERE PERSONTYPE = 1)
p.campbell
looks good when your query is a one liner, however if the select is larger with multiple joins, then not so much. Not bad though.
Phil
Indeed, in the case of a larger select statement with multi joins, I'd make it a CTE.
p.campbell
+3  A: 

Use:

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!'
OMG Ponies
@p.campbell: Thx - corrected; the OPs syntax threw me off
OMG Ponies
I like the ALL keyword, it really emphasizes what I'm trying to do. Not a bad idea. Only works with INT though.
Phil
@Phil: Good point, our Canadian postal codes wouldn't work well with MIN/MAX...
OMG Ponies
OMG a Canadian!
pilcrow
@pilcrow: http://www.youtube.com/watch?v=bpj1zgyfScM
OMG Ponies
@OMG Ponies: Haven't seen that commercial in a while, thanks for posting, hilarious!
Phil
+2  A: 

Jumping in:

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!' 
8kb
I like the idea. The thing that bugs me is that why doesn't the ALL keyword work as one would expect with an empty set. Kinda renders it useless for many use cases. I would like to keep using it for readability.
Phil
Implemented your code in my real world case so you get the check. Thanks!
Phil