如何在存储过程中将SP参数用作表和列名称

时间:2013-01-11 14:23:56

标签: sql sql-server tsql stored-procedures

create procedure <procedure>
(
    @tbl as varchar(50)='product',
    @col as varchar(50)='proid'
)
as 
begin
    select @col from @tbl 
end

1 个答案:

答案 0 :(得分:2)

因为默认情况下不能使用参数化表或列名。你只能通过在字符串中创建动态SQL然后执行该字符串来实现它。例如,

create procedure <procedure>
(
    @tbl as varchar(50)='product',
    @col as varchar(50)='proid'
)
as 
begin

   Declare @SQL VarChar(1000)

   SET @SQL = 'select ' + @col + ' from ' + @tbl 
   Exec ( @SQL)
end