Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何将select语句的结果存储到变量中?_Sql_Sql Server - Fatal编程技术网

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

Sql 如何将select语句的结果存储到变量中?,sql,sql-server,Sql,Sql Server,我尝试了以下代码: DECLARE @rec_count int Set @rec_count= select 1 但它显示出错误 Select附近的语法不正确 要么: set @rec_count = (select 1) 或 将表中的计数分配给变量的示例: set @rec_count = (select COUNT(*) from master..spt_values) select @rec_count = COUNT(*) from master..spt_values

我尝试了以下代码:

DECLARE @rec_count     int
Set @rec_count=  select 1
但它显示出错误

Select附近的语法不正确

要么:

set @rec_count =  (select 1)

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

set @rec_count = (select COUNT(*) from master..spt_values)
select @rec_count = COUNT(*) from master..spt_values
但是,如果只想为变量赋值,则不需要任何select语句:

set @rec_count = 1

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

DECLARE @rec_count  INT
SELECT @rec_count = 1
我们可以从select语句中获得多个值,如下所示

DECLARE @rec_count  INT
DECLARE @date DATETIME

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

如果您正在尝试获取记录计数,这与您正在尝试的操作类似,您可以执行以下操作:

declare @rec_count int
select @rec_count = count(1) from [your_table] -- where some condition is met
注意:使用count1而不是count*,因为在获取计数时,只选择一个列比选择所有列更快

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

返回受上一条语句影响的行数

因此,例如,如果您正在执行更新或选择,并且希望知道有多少行受到影响,则SQL Server将自动将其存储在@@ROWCOUNT中


如何将select语句的结果存储到变量中?此答案不使用任何select语句。它更正了语法错误。将变量的值设置为1不需要选择。问题标题显示SELECT语句的结果它被称为XY问题:@TabAlleman虽然我同意不需要选择来指定变量的值,但OP并不是这样要求的。这可能是一个XY问题,但也可能不是。你能告诉我什么是spt_值吗?@user3868487这是一个系统表;这其实并不重要,我只是把它作为一个例子——它可以是任何表或任何你想分配的东西。你需要更具体一些。您是否试图存储单行的单个标量值,即行计数?或者您正在尝试存储多个列和/或行?这些问题的答案各不相同,到目前为止,人们只回答了与单个标量值相关的问题。那么,你想完成什么?
DECLARE @rec_count  INT
SELECT @rec_count = 1
DECLARE @rec_count  INT
DECLARE @date DATETIME

SELECT @rec_count = 1, @date = GETDATE()
declare @rec_count int
select @rec_count = count(1) from [your_table] -- where some condition is met
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