SQL服务器定义局部变量

时间:2014-07-08 14:46:04

标签: sql-server sql-server-2008

我在SQL Server中有以下查询

SELECT name,id FROM [someDatabase] 
where id like 'testName'

现在我想在另一个查询中使用name和id,并将name定义为NAME,id定义为ID

SELECT DISTINCT vision FROM [someDatabase] WHERE name = NAME 

And id = ID

我不熟悉SQL服务器语法。如何将这两个定义为局部变量?

提前致谢。

2 个答案:

答案 0 :(得分:1)

您需要声明变量以保存数据:

DECLARE @name VARCHAR(100),
        @id   INT

然后您可以在select语句中分配这些变量。请注意,此查询不会产生任何输出。

SELECT @name = name,@id = id FROM [someDatabase] 
where id like 'testName'

最后,您可以在查询中使用这些值

SELECT DISTINCT vision FROM [someDatabase] WHERE name = @name 
And id = @id

答案 1 :(得分:0)

SELECT DISTINCT vision FROM [somedatabase] 
WHERE name IN (SELECT name FROM [someDatabase] where id like 'testName')
AND id IN (SELECT id FROM [someDatabase] WHERE id LIKE 'testName')