如何从select语句的结果中为变量赋值?

时间:2012-09-12 14:13:42

标签: sql tsql variables

SELECT TOP 1 [FirstName], [LastName]
FROM [table]

DECLARE @firstName VARCHAR(25)

运行上面的查询后,我想将从查询中带回的[FirstName]分配给@firstName。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

DECLARE @firstName VARCHAR(25) 

SELECT TOP 1 @firstName = [FirstName] FROM [table] 

答案 1 :(得分:0)

像这样:

DECLARE @firstName VARCHAR(25), @LastName VARCHAR(25)

SELECT TOP 1 @firstName = [FirstName], @LastName = [LastName]
FROM [table]

答案 2 :(得分:0)

使用SET从查询中分配值:

DECLARE @firstName VARCHAR(25)

SET @firstName = (SELECT TOP 1 [FirstName] FROM [table])