CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Darrell Norton's Blog [MVP]

Fill in description here...

Determining if a T-SQL variable is in a range of values

Here’s a neat little T-SQL trick.

You can use set-based operations on variables. For example, copy this in SQL Server Query Analyzer and running it prints “Vowel” to the output window:

DECLARE @letter char(1)
SELECT @letter = 'A'
IF @letter IN ('A', 'E', 'I', 'O', 'U')
            PRINT 'Vowel'
ELSE
            PRINT 'Consonant'

Yes the example is simple, but where I find it useful is with a varchar variable passed into a stored proc called by other stored procs. I need to check for one of 10 values (out of hundreds), and this is a whole lot easier than writing
IF @letter = ‘A’ OR @letter = ‘E’ etc.



Comments

Jason Row said:

Grrr, it's too early in the morning. I'm sure people can figure out the URL even though the link doesn't work. Good thing it's Friday.
# October 7, 2004 12:57 AM

Darrell said:

The correct link for readers is http://thedailywtf.com/

And this was an *example*, not the actual codes, sheesh. :)
# October 7, 2004 1:34 AM

Jason Row said:

I'm going to take a closer look at your URLScanWatcher code now to see what I can submit!
# October 7, 2004 3:39 AM

Steve said:

Or put it in a function and call it directly from a SELECT statement. Just be mindful of the implications of OR conditions on the query optimizer, because this is essentially what an 'IN' statement is.
# October 7, 2004 7:56 AM

me said:

"...be mindful of the implications or OR conditions..." Come on, Steve. Either you need to meet the condition or you don't.
# October 14, 2004 1:23 AM
Check out Devlicio.us!