在INSERT语句中为表名使用变量

时间:2012-10-25 15:27:06

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

  

可能重复:
  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的存储过程中使用此脚本。

4 个答案:

答案 0 :(得分:6)

我认为你需要使用串联将参数值插入到字符串中:

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

或使用sp_executesql

答案 1 :(得分:1)

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+''')';

答案 2 :(得分:0)

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

答案 3 :(得分:0)

INSERT有两种选择:

  1. 要么插入显式值 -

    INSERT INTO dbo.YourTable(list of columns) 
    VALUES (list of values)
    
  2. 或者使用返回适当列数的SELECT命令插入:

    INSERT INTO dbo.YourTable(list of columns)
      SELECT (list of columns)
      FROM dbo.SomeOtherTable
      WHERE somecondition
    
  3. 但是你不能混合两者 - 你不能拥有VALUES(....)然后在那里提供SELECT声明。使用选项#1 #2 - 选择一个。