//
you're reading...
SQL Server, T-SQL

Set it or Select it?

I get asked this question quite frequently regarding which to use in a T-SQL statement, SET or SELECT. I personally use SET 90% of the time, if for not other reason then my development background(readability).

Here’s what I know about the differences between SET  & SELECT:

  • SET is the ANSI standard for assigning values to variables, SELECT is not.
  • SET allows only one variable assignment at a time, SELECT allows for multiple variable assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you’d likely never know why something was going wrong elsewhere – have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it’s previous value)

declare @var varchar(20)

set @var = ‘Toast’

Set @var = (select name from master.sys.tables where name = ‘Jelly’)

select @var /* @var is now NULL */

set @var = ‘Toast’

select @var = name from master.sys.tables where name = ‘Jelly’

select @var /* @var is still equal to ‘Toast’ */

  • As far as speed differences – there are no direct differences between SET and SELECT. However SELECT’s ability to make multiple assignments in one shot does give SELECT a speed advantage over SET.

ldgaller2

Advertisements

About ldgaller

Accomplished Data Warehouse Architect, DBA and Software Architect with over 15 years of professional experience and demonstrated success designing and implementing solutions that improve business functionality and productivity. Highly diverse technical background with proven ability to design, develop and implement technology on an enterprise level. I approach all projects with passion, diligence, integrity, and exceptional aptitude.

Discussion

No comments yet.

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

%d bloggers like this: