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

时间:2022-02-07 14:21:08

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?

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

3 个解决方案

#1


76  

DECLARE @a int;
DECLARE @b int;

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

#2


10  

Do it like this:

像这样做:

Declare @a int;
Declare @b int;

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

PRINT @a
PRINT @b

#3


1  

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.

如果您在存储过程中执行此操作并且不希望在输出结果集中使用select的结果,则需要使用单词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';

#1


76  

DECLARE @a int;
DECLARE @b int;

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

#2


10  

Do it like this:

像这样做:

Declare @a int;
Declare @b int;

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

PRINT @a
PRINT @b

#3


1  

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.

如果您在存储过程中执行此操作并且不希望在输出结果集中使用select的结果,则需要使用单词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';