sql server在变量中存储select的结果?

时间:2013-04-11 21:00:34

标签: sql sql-server sql-server-2008

我正在开发一个功能。 select语句只返回一行,包含一列,比如说int。如何将这个int存储在声明的变量中,以便我的函数可以返回变量?

select sum(table_name.col1) -- this line returns only one int. How to store that
--in a declared variable ? 
from
(select 
col1, col2
--code here
)table_name

2 个答案:

答案 0 :(得分:18)

DECLARE @Varname int
SELECT @Varname = SUM(table_name.col1) FROM etc
SELECT @Varname

答案 1 :(得分:4)

DECLARE @result INT

SELECT @result = sum(table_name.col1)
from
(select 
 col1, col2
 --code here
)table_name