在SQL Server存储过程中使用参数传递表名

问题描述:

我想创建一个将更新表的存储过程。该过程将连接两个表,我想使用变量传递表名(@tablename)。产生在SQL Server存储过程中使用参数传递表名

此错误:

必须声明表变量 “@tablename”。

我的代码:

Create Procedure dbo.SpUpdate (@TableName varchar(50)) 
as 
begin 
    set @tablename='Customer' 

    Update a 
    Set AgentNumber = '5', 
    From dbo.CustomerList a 
    join @tablename b on a.customerid = b.customerid 
end 
+0

退房动态SQL –

+0

更新问题,包括你是什么数据库。很确定你会*在这里使用动态sql ...虽然我建议你问你为什么这样做,如果有更好的方法来实现你想要的东西。 – Twelfth

+0

除了下面的修复程序,您还有其他一些问题。在更新的第一行后面有逗号,但您只更新单个列。如果你有一个区分大小写的排序规则,这将失败,因为TableName tablename –

你可以使用这个脚本:

Create Procedure dbo.SpUpdate (@TableName varchar(50)) 
as 
begin 

DECLARE @SqlText NVARCHAR(MAX) 

SET @SqlText = 
'Update a 
Set AgentNumber=''5'', 
From dbo.CustomerList a 
join ' + QUOTENAME(@tablename) + ' b 
on a.customerid= b.customerid' 

EXEC sp_executesql @SqlText 

end