How can we assign local variable in sub query SQL Server

user3916664 picture user3916664 · Oct 4, 2014 · Viewed 14k times · Source

I tried to set a value to variable in sub query but it doesn't work.

Here is my query:

declare @val1 int
declare @val2 int

select @val1 = sum(column1) 
,(select @val2 = (select sum(column2) from table2))
,(@val1+@val2)Result
from table 1 

What I want to do is setting @val2 for sub query help me please I meant set in Sub query not separate select statement

Answer

Vojtěch Dohnal picture Vojtěch Dohnal · Oct 4, 2014

Just use 3 separate selects:

select @val1 = sum(column1) from table1 
select @val2 = sum(column2) from table2
select (@val1+@val2) as Result

Or you can also write 2 selects:

 select @val1 = sum(column1), 
        @val2 = (select SUM(column2) from table2)
 from table1
 select (@val1 + @val2) Result

But not just 1 select:

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

If you need to accomplish all in one select and return a recordset, do not use variables, do it like this:

SELECT sum1 + sum2 FROM (
    select sum(column1) as sum1, 
           (select SUM(column2) from table2) as sum2
    from table1
) subquery