【问题标题】:Using a variable for the table name in an INSERT statement [duplicate]在 INSERT 语句中使用表名的变量[重复]
【发布时间】:2012-10-25 15:27:05
【问题描述】:

可能重复:
Is there a way to specify table name as a string?

以下脚本将被正确执行:

DECLARE @SourceDB sysname, @SourceTable sysname, 
        @UserID NVARCHAR(500), @DMLType CHAR(1), @SourceIdent uniqueidentifier, @ChangedData XML,
        @SQL as NVARCHAR(MAX)

-- xml datatype and its capabilities rock
SELECT  @SourceDB = T.c.query('/AuditMsg/SourceDb').value('.[1]', 'sysname'),
        @SourceTable = T.c.query('/AuditMsg/SourceTable').value('.[1]', 'sysname'),
        @SourceIdent = T.c.query('/AuditMsg/SourceIdent').value('.[1]', 'uniqueidentifier'),
        @UserID = T.c.query('/AuditMsg/UserId').value('.[1]', 'NVARCHAR(50)'),
        @DMLType = T.c.query('/AuditMsg/DMLType').value('.[1]', 'CHAR(1)'),
        @ChangedData = T.c.query('*')
FROM    @msgBody.nodes('/AuditMsg/ChangedData') T(c)

INSERT INTO dbo.AVE_Stamm(SourceDB, SourceIdent, UserID, DMLType, ChangedData)
SELECT @SourceDB, @SourceIdent, @UserID, @DMLType, @ChangedData

但是当我将INSERT 语句更改为

SET @sql = 'INSERT INTO @SourceTable (SELECT @SourceDB, @SourceIdent, @DMLType, @ChangedData, @UserID)';
EXEC (@sql);

它不再工作了。谁能帮帮我,这里有什么问题?

我在 SQL Server 2008 R2 的存储过程中使用此脚本。

【问题讨论】:

    标签: sql-server tsql stored-procedures sql-server-2008-r2


    【解决方案1】:

    我认为您要么需要使用连接将参数值插入到字符串中:

    SET @sql = 'INSERT INTO ' + @SourceTable + ' SELECT ....';
    EXEC (@sql);
    

    或使用sp_executesql

    【讨论】:

      【解决方案2】:
      SET @SQL = 'INSERT INTO '+@SourceTable+' (VALUES '''+@SourceDB+''', '''+
          @SourceIdent+''', '''+@DMLType+''', '''+@ChangedData+''', '''+@UserID+''')';
      

      一旦将字符串传递到 EXECUTE,变量就不再在作用域内。您需要通过连接值来构建传入的字符串。此外,对于这种类型的 INSERT,VALUES 比 SELECT 更合适。

      如果您的 XML 可能包含引号字符,则需要执行以下操作...

      SET @SQL = 'INSERT INTO '+@SourceTable+' (VALUES '''+@SourceDB+''', '''+
          @SourceIdent+''', '''+@DMLType+''', '''+REPLACE(@ChangedData,'''','''''')+''', '''+@UserID+''')';
      

      【讨论】:

      • 您能否提供一些背景/推理背后的答案,以使 OP 受益。
      • 谢谢。但是@SourceIdent 是 uniqueidentifier 类型,@ChangedData 是 xml 类型 - 我必须做什么才能在您的解决方案中使用此变量(字符串连接似乎存在问题)
      • 这些类型通常在 TSQL 中隐式转换为字符串。你遇到了什么错误?它可以是嵌入在 XML 中的引号字符。我在解决方案中添加了代码来解决这个问题。
      【解决方案3】:

      您的代码在我看来并不完整,但您应该使用sp_ExecuteSQL 并定义语句的参数。有关 sp_ExecuteSQL 的详细信息,请参阅 MSDN。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-20
        • 1970-01-01
        • 2016-05-19
        • 2020-04-16
        • 2022-09-23
        • 2017-11-09
        • 1970-01-01
        相关资源
        最近更新 更多