10

Due to runtime I want to asign the columns of a single-row-resultset to multiple variables at once in a SQL-Server stored Procedure. I want to replace the last 2 lines of the following code:

Declare @A int
Declare @B int
Select @A = (Select Col1 From Table1 Where ID=1234)
Select @B = (Select Col2 From Table1 Where ID=1234)

Since in this version the program would search twice for the ID=1234 i want to do something like

Select @A, @B = (Select Col1, Col2 From Table1 Where ID=1234)

But i can't figure out the correct syntax for this.

4 Answers 4

9

You can do like this

Select @A =Col1,@B=Col2  From Table1 Where ID=1234
Sign up to request clarification or add additional context in comments.

Comments

3

Just comma separate them and have the assignments directly in the SELECT rather than using a subquery:

Select @A = Col1,@B =  Col2 From Table1 Where ID=1234

See select @local_variable:

SELECT { @local_variable { = | += | -= | *= | /= | %= | &= | ^= | |= } expression } [ ,...n ] [ ; ]

Where the [,...n] means you can repeat the preceding part as many times as you want to, separating each repeat with a comma.

Comments

2

For separate assignment statement, you need to use SET

DECLARE @A INT
DECLARE @B INT
SET @A = (SELECT Col1 FROM Table1 WHERE ID = 1234)
SET @B = (SELECT Col2 FROM Table1 WHERE ID = 1234)

For single assignment statement, you can use

SELECT @A = Col1, @B = Col2 FROM Table1 WHERE ID = 1234

Comments

-2

You will want to use a cursor for iterating over the data set, even if it contains only one row. See http://stevestedman.com/2013/04/t-sql-a-simple-example-using-a-cursor/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.