如何将select语句的结果存储到变量中?

时间:2014-10-16 13:17:21

标签: sql sql-server

我尝试使用以下代码:

DECLARE @rec_count     int
Set @rec_count=  select 1

但显示错误

  

“选择”附近的语法不正确。

4 个答案:

答案 0 :(得分:3)

或者:

set @rec_count =  (select 1)

select @rec_count = 1

将表中的计数分配给变量的示例:

set @rec_count = (select COUNT(*) from master..spt_values)
select @rec_count = COUNT(*) from master..spt_values

但是,如果您只想为变量赋值,则不需要任何select语句:

set @rec_count = 1

declare @rec_count int = 1

答案 1 :(得分:0)

要将select语句的结果存储到变量中,请参阅下面的

DECLARE @rec_count  INT
SELECT @rec_count = 1

我们可以从select语句中获取多个值,如下所示

DECLARE @rec_count  INT
DECLARE @date DATETIME

SELECT @rec_count = 1, @date = GETDATE()

答案 2 :(得分:0)

如果您正在尝试获取记录计数,这看起来就像您尝试做的那样,您可以这样做:

declare @rec_count int
select @rec_count = count(1) from [your_table] -- where some condition is met

注意:使用count(1)代替count(*),因为在获取点数时,只需选择一列而不是全部。

或者,如果此计数是某些插入/更新/选择/删除的结果,则可以使用@@ROWCOUNT,其中:

  

返回受最后一个语句影响的行数。

因此,例如,如果您正在执行updateselect并想知道受影响的行数,则SQL Server会自动将其存储在@@ROWCOUNT中。

declare @rec_count int

-- some table change
update your_table
set col1 = 1
where col1 = 0

set @rec_count = @@ROWCOUNT
-- select @@ROWCOUNT <-- this would return the number of rows updated

答案 3 :(得分:-2)

DECLARE @rec_count int;
Set @rec_count = 1;
相关问题