Skip navigation.

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

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.


This Blog Hosted On: http://www.DotNetJunkies.com/