Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Assigning a variables value

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-06-10 : 00:47:03
Joe writes "What is the correct method of assigning a variables value?
Is it better to use, for example;

DECLARE @iI int

SELECT @iI = 1
OR
SET @iI = 1

Thanks in advance,
Joe."

Nazim
A custom title

1408 Posts

Posted - 2002-06-10 : 01:52:16
AFAIK there wouldnt be a performace difference if you are trying to assing values in either of the ways.

but remember, you can use set only when you have a explicit value but using select you can query from a object and assign the value.

eg:

set @i=1
or
select @i=1 doesnt makes much difference

but
set @i= max(studentno) from students
will generate a error indicating incorrect syntax

where as
select @i= max(studentno) from students
will work perfectly.

HTH


-------------------------
What lies behind you and what lies ahead of you are small matters compared to what lies within you.-Ralph Waldo Emerson
Go to Top of Page

jasper_smith
SQL Server MVP & SQLTeam MVY

846 Posts

Posted - 2002-06-10 : 05:39:20
Plus with select you can assign values to multiple variables at once
i.e.

declare @err int
declare @cnt int

select * from pubs..titles
select @err=@@ERROR,@cnt=@@ROWCOUNT

without using select here you can't get accurate error and rowcount info because if you get @err first then rowcount will be wrong and if you get @cnt first then @err will reflect any errors in the "set @cnt=@@ROWCOUNT" statement rather than what you are interested in.

i.e.

*****WRONG WAY ******
declare @err int
declare @cnt int

select * from pubs..titles
set @err=@@ERROR -- okay, will contain correct error
set @cnt=@@ROWCOUNT -- will contain 1 (for set @err=@@ERROR )

HTH
Jasper Smith

Go to Top of Page
   

- Advertisement -