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

时间:2012-02-03 11:14:41

标签: sql sql-server-2005

我想这样做:

Declare @a int;
Declare @b int;

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

PRINT @a
PRINT @b

但这是无效的语法。如何在一个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

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

3 个答案:

答案 0 :(得分:91)

DECLARE @a int;
DECLARE @b int;

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

答案 1 :(得分:12)

这样做:

Declare @a int;
Declare @b int;

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

PRINT @a
PRINT @b

答案 2 :(得分:3)

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

Declare @a int;
Declare @b int;

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

它也可以这样使用:

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