Wednesday, February 22, 2012

What is the difference between SET and SELECT when assigning values to variables, in T-SQL?

Though you can assign values to local variables using either SET/SELECT,
There are few differences.

SET can be used for assigning one variable at a time whereas Select can be used for
multiple variable Assignments

Moving on to other differences between SET and SELECT: When using a query to
populate a variable, SET will fail with an error, if the query returns more than one
value. But SELECT will assign one of the returned rows and mask the fact that the
query returned more than one row. As a result, bugs in your code could go unnoticed
with SELECT, and this type of bugs are hard to track down too.

Here is another difference with respect to assigning values based on a query,
especially when the query doesn't return any rows. When Assigning Variable using
SET for a value returned by a subquery, and sub query does not return any value,
null will be assigned to variable. In case of SELECT, if subquery does not return any
rows, previously assigned value will still remain.

A single SELECT statement assigning values to 3 different variables, is much faster
than 3 different SET statements assigning values to 3 different variables. In this
scenario, using a SELECT is at least twice as fast, compared to SET.

No comments:

Post a Comment