Apr 20, 2008

SET VS SELECT - When to use what?


Let us observe the following two queries :

DECLARE @CID int
SET @CID =(Select CID from Customers)
SELECT @CID = (Select CID from Customers)

Both work well as far as a single row is being returned. When multiple rows are returned, the SET fails , whereas SELECT is the way to go. If the query returns nothing, SET assigns NULL as the value of the variable, whereas SELECT ignores it. SELECT is also capable of making multiple assignments.

Usually when a single value is to be assigned to a variable, go in for SET. However if you are setting the value using a query, as shown above, then its better to go in for SELECT as the rows returned 'could' be more than one, which can be handled by SELECT but not SET.

Another difference is that SET is ANSI standard, SELECT is not.

As a rule of thumb, I go ahead with SELECT when I have to set multiple variables. Else if I have to only set one variable, I am better off with SET.

Here's a good read about SET VS SELECT performance
http://www.sqlmag.com/Articles/ArticleID/94555/94555.html

Submit this story to DotNetKicks

Related Posts In This Category



Widget by Hoctro | Jack Book

 
  Feedback:

comments

3 Responses to "SET VS SELECT - When to use what?"
  1. Boyan Kostadinov said...
    April 25, 2008 5:49 AM

    A shorter variation of:
    SELECT @CID = (Select CID from Customers)
    is
    SELECT @CID = CID from Customers

  2. Bart Czernicki said...
    April 27, 2008 8:58 AM

    Multiple assignments is by far the biggest reason to use select over set. It gives you a huge performance gain if you are setting a lot of variables for a big sproc/script

    declare @test int, @test2 int;
    set @test = 1, @test2 = 2; --doesn't work
    select @test = 1, @test2 = 2; -- works

  3. Suprotim Agarwal said...
    April 27, 2008 11:02 AM

    Thanks Boyan and Bart for the informative comments..

 

Copyright 2009 All Rights Reserved SQL Server Curry by Suprotim Agarwal