SQL 在一个 SELECT 语句中设置两个标量变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9127775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:14:17  来源:igfitidea点击:

Setting two scalar variables in one SELECT statement?

sqlsql-server-2005

提问by Oliver

I want to do this:

我想做这个:

Declare @a int;
Declare @b int;

SET @a,@b = (SELECT StartNum,EndNum FROM Users Where UserId = '1223')

PRINT @a
PRINT @b

But this is invalid syntax. How do I set multiple scalar variables in one select statement? I can do:

但这是无效的语法。如何在一个 select 语句中设置多个标量变量?我可以:

Declare @a int;
Declare @b int;

SET @a = (SELECT StartNum FROM Users Where UserId = '1223')
SET @b = (SELECT EndNum FROM Users Where UserId = '1223')

PRINT @a
PRINT @b

But this will take twice as long. What is the fastest way?

但这需要两倍的时间。最快的方法是什么?

回答by juergen d

DECLARE @a int;
DECLARE @b int;

SELECT @a = StartNum, @b = EndNum 
FROM Users 
WHERE UserId = '1223'

回答by aF.

Do it like this:

像这样做:

Declare @a int;
Declare @b int;

SELECT @a=StartNum,@b=EndNum FROM Users Where UserId = '1223'

PRINT @a
PRINT @b

回答by rvazquezglez

If you are doing this in a stored procedure and don't want the result of the select in an output resultset you will need to use the word INTO.

如果您在存储过程中执行此操作并且不希望在输出结果集中选择的结果,您将需要使用单词 INTO。

Declare @a int;
Declare @b int;

SELECT StartNum, EndNum 
FROM Users 
Where UserId = '1223'
INTO @a, @b;

It also can be used like this:

它也可以这样使用:

SELECT StartNum, EndNum 
INTO @a, @b
FROM Users 
Where UserId = '1223';