February 22, 2008 at 3:31 am
Could someone tell me the difference between the following two syntacts
--Using Set
Declare @MyVar int
Set @MyVar=1000
--Using Select
Declare @MyVar int
Select @MyVar=1000
Are there situations in which Set should be used and others wher Select should be?
Are there implications, performance or otherwise, of using one over the other?
tia
Terry
February 22, 2008 at 4:44 am
February 22, 2008 at 6:36 am
Edward (2/22/2008)
have a look at thishttp://ryanfarley.com/blog/archive/2004/03/01/390.aspx
Hope it helps
Pretty good explanation of SET vs SELECT... horrible method of creating a split function. Use a Tally table, instead.
--Jeff Moden
Change is inevitable... Change for the better is not.
February 22, 2008 at 11:32 am
i'll check when I get home - blogs are blocked at work
February 25, 2008 at 12:02 am
Hi,
Is it a homework???:-)
Set can be used only to intialize a single variable.
Select can be used to intialize a single variable or more than that..
February 25, 2008 at 1:48 am
And something for the future, if you will move to SS2008 🙂
I like using select statements when initializing a large number of freshly declared variables. This results in fewer lines of T-SQL. SS2008 will allow to skip even the select line, as it finally allows you to set variable values in the declaration statement. E.g.
declare @a int = 1, @b-2 int = 2
Regards,
Andras
February 26, 2008 at 9:23 am
Haaa... I like that new SQL 2008 declare and set function.
One more thing to answer your question. Let's say you need both the number of rows affected and the error status code right after an UPDATE. You have to use
DECLARE @li_RowCount int, @li_ErrCode int
SELECT @li_RowCount = @@ROWCOUNT, @li_ErrCode = @@ERROR
BECAUSE
SET @li_RowCount = @@ROWCOUNT
SET @li_ErrCode = @@ERROR
Fails.
After the first SET is executed, the @@ERROR value for the UPDATE statement is LOST. The second @@ERROR value is now what happened when the fist SET command was executed.
This is one specific case where SELECT is preferable over the SET statement even when setting a single local variable
Otherwise, when assigning a value to a local variable, I prefer to use the SET keyword.
Again this is a personal preference.
February 26, 2008 at 9:39 am
And one more thing for the purists 🙂 Using SELECT to assign variables in not part of the SQL standard. For some it does matter 🙂 Though sometimes using SELECT is really useful (like J mentioned)
Andras
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply