Don’t Use Rand() function in CASE Expressions


When you use Rand function in CASE expression, you may have unexpected results. Here is a discussion for this issue:
http://social.msdn.microsoft.com/Forums/en/transactsql/thread/81a5c057-bc0c-4c56-a9fe-9be11eedb19d

I have included whatI have found from Sybase documentation:
http://manuals.sybase.com/onlinebooks/group-as/asg1250e/sqlug/@Generic__BookTextView/39235;pt=39091

My input for the thread:
The return value NULL is a design behavior when you use Rand() function in CASE Expression (it seems it is inherited from Sybase product and my guess is a standard compliance behavior). You will get some unexpected results, in your case it is the NULL value.

You can use a variable to pass the value to use in the CASE Expression:

Declare @num int=CAST((50  * RAND() + 1) as int) 
SELECT CASE @num
when 1 then 'New York'
when 2 then 'Los Angeles'
--..
ELSE
'Unknown'
END

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s