将查询中的单个结果存储到SQL中的变量中

时间:2014-07-11 13:42:33

标签: sql sql-server variables

我有这张桌子:

id     Name              Age 
------ ----------------- ----
10015  Phill             12
10016  Anne              14

我只需要菲尔的年龄。所以我这样做:

SELECT Age FROM Persons WHERE id = 10015

但我需要将该信息保存到变量中。

如果我这样做:

DECLARE @age Int
SET @age = SELECT Age FROM Persons WHERE Name LIKE 'Phill'

我得到错误

Incorrect syntax near the keyword 'SELECT'.

2 个答案:

答案 0 :(得分:3)

SET @age = (SELECT Age FROM Persons WHERE id = 10015)

这是使用SET

SELECT语法

答案 1 :(得分:1)

以下是三种方法:

DECLARE @age Int;
SET @age = (SELECT Age FROM Persons WHERE Name LIKE 'Phill');

DECLARE @age Int;
SELECT @age = Age FROM Persons WHERE Name LIKE 'Phill';

DECLARE @age Int = (SELECT Age FROM Persons WHERE Name LIKE 'Phill');