Reputation: 1629
Is it possible to update more than one local variable in a single select?
Something like:
set
@variableOne = avg(someColumn),
@variableTwo = avg(otherColumn)
from tblTable
It seems a bit wasteful to make two separate select operations for something as trivial as this task:
set @variableOne = ( select avg(someColumn) from tblTable )
set @variableTwo = ( select avg(otherColumn) from tblTable )
Upvotes: 68
Views: 81607
Reputation: 9
SELECT DISTINCT
@Var1 = Column1,
@Var2 = Column2
FROM MyTable
WHERE Columnx = @Parm1
Upvotes: -2
Reputation: 110221
You can use SELECT assignment to assign multiple variables. This code generates a single row of constants and assigns each to a variable.
SELECT
@var1 = 1,
@var2 = 'Zeus'
You can even query tables and do assignment that way:
SELECT
@var1 = c.Column1,
@var2 = c.Column2,
FROM
Customers c
WHERE c.CustomerID = @CustomerID
Beware: This code operates like a while loop.
Prefer using SET assignment over SELECT assignment. Only use SELECT assignment when considering both scenarios above.
Upvotes: 26
Reputation: 1850
how about
SELECT @variableOne = avg(someColumn), @variableTwo = avg(otherColumn) from tblTable
it works for me just fine.
Upvotes: 1
Reputation: 56964
Something like this:
select @var1 = avg(someColumn), @var2 = avg(otherColumn)
from theTable
Upvotes: 134