gpt4 book ai didi

sql - 将表名作为参数传递

转载 作者:行者123 更新时间:2023-12-01 09:56:43 25 4
gpt4 key购买 nike

我的任务是使用要从外部来源引入的信息来更新几个表。为此,我一直在网上寻找将表名作为参数传递的方法,所有答案都很复杂和/或抛出错误(如下所示:“Incorrect syntax near 'Table' error shows)

CREATE PROCEDURE sp_Insert_Delta 
-- Add the parameters for the stored procedure here
@tableName Table READONLY

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Delete rows in MIRROR database where ID exists in the DELTA database
Delete from [S1].[MIRROR].[dbo].@tableName
Where [ID] in (Select [ID] from [S2].[DELTAS].[dbo].@tableName)

-- Insert all deltas
Insert Into [S1].[MIRROR].[dbo].@tableName
Select * from [S2].[DELTAS].[dbo].@tableName

END
GO

这个脚本在显式命名时工作得很好,那么如何参数化表名?

谢谢,

内特

最佳答案

使用动态 SQL

DECLARE @sql as varchar(4000)
SET @sql = 'Delete from [S1].[MIRROR].[dbo].' + @tableName
+ ' Where [ID] in (Select [ID] from [S2].[DELTAS].[dbo].' + @tableName + ')'
EXEC(@sql)

举个例子

关于sql - 将表名作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25124034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com