如何在T-SQL中将查询结果分配给局部变量

时间:2018-11-08 13:15:17

标签: sql sql-server tsql variables

我需要将多列的查询结果存储/分配给局部变量

例如;

declare @localVariable

select @localVariable = userId, userName, email, address 
from user;

我相信以上代码不正确!

2 个答案:

答案 0 :(得分:4)

您需要为此声明一个表变量:

DECLARE @localVariable AS TABLE
(
    userId int,
    userName varchar(10),
    email nvarchar(100),
    address nvarchar(1000)
);

INSERT INTO @localVariable (userId, userName, email, address)
SELECT userId, userName, email, address
FROM [user];

答案 1 :(得分:1)

您不能在select语句中混合使用变量赋值和数据检索。这将不起作用:

DECLARE @localVariable INT;
SELECT TOP 1 @localVariable = userId, userName FROM user;

但这会:

-- copy values from multiple columns to variables
DECLARE @localVariable1 INT;
DECLARE @localVariable2 VARCHAR(100);
SELECT TOP 1 @localVariable1 = userId, @localVariable2 = userName FROM user;