1

我想在 select 语句中使用 tablename 变量,但它给出错误

-必须声明表变量“@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

这是我的代码的快照

4

3 回答 3

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
于 2014-08-12T13:12:31.333 回答
2

您不能使用变量作为表名。当您执行select address from @tableSQL 时,期望@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
于 2014-08-12T13:25:33.823 回答
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
于 2014-08-12T13:13:13.780 回答