Difference in assignment using SELECT and SET

by Allan Svelmøe Hansen September 27, 2008 09:08

Basically – there are two ways (at least?) of selecting information into a variable from a table/select query.

You can either SELECT @Variable = COLUMN FROM TABLE or you can SET @Variable = (SELECT COLUMN FROM TABLE).

There is one big difference between the two one needs to be aware of. The first method will not set a new value to @Variable if there isn’t returned a row from the select statement – but the second one will.

This is easy to see by running a query like this where the SELECT will return no rows:

DECLARE 
@Value 
INT
DECLARE 
@i 
INT
SET 
@i 
0

WHILE 
@i 100 
BEGIN
   SELECT 
@Value MyID FROM Table_1 WHERE MyValue IS 
NULL
   
IF @Value IS 
NULL 
           
SET @Value 
@i
   
PRINT(@Value
)
   
SET @i @i 
1
END 

SET 
@i 
0
SET @Value 
0

Now the first impression will be that the values 0 to 99 will be printed out, but that is wrong. You’ll get 100 prints of 0. That is because the SELECT doesn’t return any rows so the assignment doesn’t happen, because it occurs within the SELECT statement.

Whereas if you change the query to this:

WHILE @i 100 BEGIN
   SET 
@Value (SELECT MyID FROM Table_1 WHERE MyValue IS 
NULL)
   
IF @Value IS 
NULL 
           
SET @Value 
@i
   
PRINT(@Value
)
   
SET @i @i 
1
END 

You’ll get the expected assignment of 0 to 99 when run, because the SELECT doesn't return a row, the SET will assign NULL. A big difference in the execution of the assignment.

Bookmark and Share DotnetKicks dotnetshoutout

Tags: ,

SQL

Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen | Modified by Mooglegiant

About:
Allan Svelmøe Hansen

My real name is Allan Svelmøe Hansen.
I live in Denmark, where I work as a developer for hedal:kruse:brohus using SQL Server and the .NET framework since 2004.
My primary fields of expertise is back-end data integration, database design and optimization.


       View Allan Svelmøe Hansen's profile on LinkedIn     

Disclaimer

The opinions expressed herein are my own personal opinions and thoughts and does not represent my employers view in any way, nor are my results guaranteed for all situations.
Content is presented "as is", with no warranty.