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?
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.
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.
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.
DECLARE @a int; DECLARE @b int; SELECT @a = StartNum, @b = EndNum FROM Users WHERE UserId = '1223'
Do it like this:
Declare @a int; Declare @b int; SELECT @a=StartNum,@b=EndNum FROM Users Where UserId = '1223' PRINT @a PRINT @b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With