请参阅下面的DDL:
CREATE TABLE Person (ID int identity, Name varchar(30), primary key(ID))
INSERT INTO Person (Name) VALUES ('Ian')
请参阅下面的TSQL:
Declare @ID int
Declare @Name varchar(30)
set @Name = 'Ian'
select @ID=ID FROM Person WHERE Name=@Name
Print @ID
这正如我所料,即1被打印到屏幕上。我想进行更改,以便表名是动态的,即
Declare @ID int
Declare @Name varchar(30)
Declare @TableName as varchar(30)
set @TableName= 'Person'
set @Name = 'Ian'
select @ID=ID FROM @TableName WHERE Name=@Name
Print @ID
上面的SQL显然不起作用。我意识到我必须使用TSQL。我已经尝试过使用EXEC和sp_executesql,但我只能在那里使用。我该如何实现呢。 SQL语句必须是:select @ID=ID FROM @TableName WHERE Name=@Name
。
答案 0 :(得分:1)
您需要使用动态sql。看看这里......
Declare @ID int
Declare @Name varchar(30)
Declare @TableName sysname
DECLARE @Sql NVARCHAR(MAX);
set @TableName= 'Person'
set @Name = 'Ian'
SET @Sql = N'select @ID = ID FROM ' + QUOTENAME(@TableName)
+ N' WHERE Name = @Name'
EXECUTE sp_executesql @Sql
,N'@ID int OUTPUT, @Name varchar(30)'
,@ID OUTPUT
,@Name
PRINT @ID