表名称在sql server中的select语句中的变量

时间:2014-08-12 13:08:05

标签: sql-server select stored-procedures input-parameters

我想在select语句中使用表名变量,但是它给出了错误

- 必须声明表变量“@table”

alter PROCEDURE testTblName
(
@id int,
@name varchar(50)
)
AS
BEGIN
   declare @table varchar(50)
   declare @add varchar(150)
   set @table = 'DBTest..testMaster'
   select @add = address from @table where id=@id and name=@name
END

这是我的代码的快照

3 个答案:

答案 0 :(得分:3)

您需要使用动态sql:

alter PROCEDURE testTblName
(
@id int,
@name varchar(50)
)
AS
BEGIN
   declare @table varchar(50)
   declare @add varchar(150)
   set @table = 'DBTest..testMaster'
   DECLARE @sql NVARCHAR(MAX)
   SELECT @sql = 'select @add = address from ' + @table + ' where id= ' + @id + ' and name= ' + @name
   EXEC sp_executesql @sql

END

答案 1 :(得分:2)

您不能将变量用于表名。执行select address from @table时SQL期望@table是表类型的变量,而不是标量。

你正在寻找这样的事情:

ALTER PROCEDURE testTblName
(
    @id INT,
    @name VARCHAR(50)
)
AS
BEGIN
    DECLARE @table VARCHAR(50),
            @add VARCHAR(150),
            @params VARCHAR(200),
            @sql VARCHAR(200);

    SET @params = '@add VARCHAR(50) OUTPUT';

    SET @table = 'DBTest..testMaster'

    SET @sql = 'SELECT @add = address FROM ' + @table + ' WHERE id=' + @id + ' AND name=' + @name

    EXEC sp_executesql @sql, @params, @add OUTPUT;

    ...
    ...
END

答案 2 :(得分:0)

我想,你必须给出这样的东西。

alter PROCEDURE testTblName
(
@id int,
@name varchar(50)
)
AS
BEGIN
    declare @table varchar(50)
    declare @add varchar(Max)
    set @table = 'DBTest..testMaster'

    Set  @add = 'Select address from ' + @table + ' where id = ' + CAST(@id AS VARCHAR(10)) + ' and name = ' + @name

    Exec(@add)
END