我有这张桌子:
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'.
答案 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');