SQL将多个局部变量输出到一列

时间:2016-12-19 16:24:38

标签: sql sql-server tsql

是否可以使用SQL将多个单独定义的局部变量作为单独的行输出到一列中?例如

DECLARE var1 INT = 4
DECLARE var2 INT = 5
DECLARE var3 INT = 6

然后以某种方式选择变量,如

SELECT (var1, var2, var3) AS UserIDs,
       ('u1', 'u2', 'u3') AS Names

哪会产生下表:

UserIDs | Names
   4    |  u1
   5    |  u2
   6    |  u3

2 个答案:

答案 0 :(得分:5)

使用表值构造函数

SELECT *
FROM   (VALUES (@var1,'u1'),
               (@var2,'u2'),
               (@var3,'u3')) tc (UserIDs, Names) 

答案 1 :(得分:4)

select var1 as UserID, 'u1' as Name
union all
select var2, 'u2'
union all
etc
etc