【问题标题】:Insert result of EXEC into table parameter将 EXEC 的结果插入到表参数中
【发布时间】:2019-07-28 12:45:13
【问题描述】:

在存储过程中,我有一个EXEC 语句;我想将其结果存储到一个表中。

首先我创建表参数为:

DECLARE @MyTable AS TABLE
                    (
                        [Item1] INT, 
                        [Item2] DECIMAL
                    )

然后我尝试将值插入为:

INSERT INTO @MyTable 
    EXEC [storedProcedure] @testitem = @testitem

我的问题:这是正确的方法吗?还是我需要使用动态查询?

因为我读过类似的问题,例如this,他们建议使用动态查询。

【问题讨论】:

  • 来自您提供的链接this question and answer relate to the 2000 version of SQL Server. In later versions, the restriction on INSERT INTO @table_variable ... EXEC ... were lifted and so it doesn't apply for those later versions.
  • 您使用的是当前版本的 sql server,因此链接无关紧要。表变量限制不再适用(并且多年未应用)。简短的回答 - 您的代码很好,尽管有些人会争辩说您应该始终在插入语句中指定列列表。懒惰对开发人员来说不是一个好习惯。

标签: sql sql-server tsql sql-server-2017


【解决方案1】:

您必须使用动态查询。

DECLARE @Sql AS VARCHAR(MAX);
SET @Sql='EXEC storedProcedure @testitem = @testitem'
INSERT INTO @MyTable ([Item1], [Item2]) EXEC(@Sql)
SELECT * FROM @MyTable;

断言上述内容,我只是想进一步阅读......并找到了这个较旧的线程。我敢打赌,进一步分析它会很有帮助。 Insert results of a stored procedure into a temporary table

【讨论】:

  • 作为 OP 的链接状态,对表变量的限制很久以前就被删除了(可能是 2008 年)。没有要求或实际需要(在这种情况下)使用动态 sql。
猜你喜欢
  • 2021-02-12
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多