我想创建一个更新表的存储过程。该过程将连接两个表,我想使用变量(@tablename
)传递表名。
生成此错误:
必须声明表变量“@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 :(得分:2)
您可以使用此脚本:
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