Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting two scalar variables in one SELECT statement?

I want to do this:

Declare @a int; Declare @b int;  SET @a,@b = (SELECT StartNum,EndNum FROM Users Where UserId = '1223')  PRINT @a PRINT @b 

But this is invalid syntax. How do I set multiple scalar variables in one select statement? I can do:

Declare @a int; Declare @b int;  SET @a = (SELECT StartNum FROM Users Where UserId = '1223') SET @b = (SELECT EndNum FROM Users Where UserId = '1223')  PRINT @a PRINT @b 

But this will take twice as long. What is the fastest way?

like image 484
Oliver Avatar asked Feb 03 '12 11:02

Oliver


People also ask

How do I assign multiple values to a variable in SQL?

Assigning multiple values to multiple variables If you have to populate multiple variables, instead of using separate SET statements each time consider using SELECT for populating all variables in a single statement. This can be used for populating variables directly or by selecting values from database.

Can you DECLARE multiple variables in SQL?

Regarding feature of SQL Server where multiple variable can be declared in one statement, it is absolutely possible to do. From above example it is clear that multiple variables can be declared in one statement. In SQL Server 2008 when variables are declared they can be assigned values as well.

How do you assign a value to a variable in a SELECT statement in SQL?

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.


2 Answers

DECLARE @a int; DECLARE @b int;  SELECT @a = StartNum, @b = EndNum  FROM Users  WHERE UserId = '1223' 
like image 139
juergen d Avatar answered Sep 18 '22 04:09

juergen d


Do it like this:

Declare @a int; Declare @b int;  SELECT @a=StartNum,@b=EndNum FROM Users Where UserId = '1223'  PRINT @a PRINT @b 
like image 45
aF. Avatar answered Sep 22 '22 04:09

aF.