从表中声明动态变量

时间:2014-11-04 09:57:14

标签: sql sql-server-2008 dynamic declare

我想将表格中的动态SQL变量DECLARE。 基本上我有一个像这样的“假设”表

City   BranchID Name
London 101      London Branch
Munich 102      Munich Branch

我已经尝试过了:

DECLARE @Cit varchar(75)
SET @Lob = 'London'

SET @ID= 'SELECT BranchID FROM dbo.assumptions WHERE city = @city'
SET @Name= 'SELECT Name FROM dbo.assumptions WHERE city= @city'

EXECUTE sp_executesql @ID, N'@city nvarchar(75)', @city= @city
EXECUTE sp_executesql @Name_Net, N'@city nvarchar(75)', @city= @city

这给了我正确的结果 101和伦敦分行

事情是我想稍后使用那些变量,例如

SELECT * From Sales where BranchID = @ID

我知道该怎么做。但是现在这给了我

SELECT * From Sales where BranchID = SELECT BranchID FROM dbo.assumptions WHERE city = 'London'

这当然不起作用。我需要@ID才能得到'101'

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

使用SubQuery

SELECT * From Sales where BranchID in( SELECT BranchID FROM dbo.assumptions WHERE city = 'London')

答案 1 :(得分:0)

DECLARE @city VARCHAR(75),
        @string1 NVARCHAR(MAX),
        @string2 NVARCHAR(MAX),
        @ID INT,
        @Name VARCHAR(100)

SET @string1= 'SELECT @ID = BranchID FROM dbo.assumptions WHERE city = @city'
SET @string2= 'SELECT @Name = Name FROM dbo.assumptions WHERE city= @city'  

EXECUTE sp_executesql @string1, N'@ID int output, @city nvarchar(75)',@ID OUTPUT, @city= @city
EXECUTE sp_executesql @string2, N'@Name varchar(100) output, @city nvarchar(75)',@Name OUTPUT, @city= @city

SELECT @ID,@Name

P.S。可能有一些编译错误,因为我没有;实际上有这些表