【问题标题】:Why can't I run INSERT EXEC on a table variable in a T-SQL function?为什么我不能在 T-SQL 函数中的表变量上运行 INSERT EXEC?
【发布时间】:2017-10-07 10:12:40
【问题描述】:

我的函数如下所示:

CREATE FUNCTION fn_FileSys_DirExists(@dirName AS nvarchar(260))
RETURNS bit
AS
BEGIN
    DECLARE @dirExists int
    DECLARE @fileResults TABLE
    (
        file_exists int,
        file_is_a_directory int,
        parent_directory_exists int
    )

    INSERT @fileResults (file_exists, file_is_a_directory, parent_directory_exists)
    EXEC master.dbo.xp_fileexist @dirName

    SELECT @dirExists = file_is_a_directory FROM @fileResults
    RETURN @dirExists
END

当我尝试执行上述 SQL 时,出现以下错误:

在 功能。

我认为函数中对表变量的操作不被认为是副作用操作?

【问题讨论】:

  • 我不确定您是否可以在函数内执行存储过程。如果我是正确的,那不是插入,而是exec 本身。
  • @ZoharPeled 是的,我很遗憾地怀疑你可能是对的。
  • 好吧,事实证明我可能是对的,as this SO post suggests
  • @ZoharPeled 你可以从函数中执行一些扩展的过程。您链接的答案执行master..xp_cmdshell。
  • @MartinSmith 是的,我见过。我也看到它非常不推荐。

标签: sql-server tsql sql-server-2012 sql-function table-variable


【解决方案1】:

INSERT ... EXEC 是一个副作用运算符,因为它最终会在后台创建一个临时表。

这是the execution plan for this dbfiddle中显示的参数表扫描的背后

有关详情,请参阅The Hidden Costs of INSERT EXEC。

最好编写一个 CLR 函数来执行此操作。

【讨论】:

    猜你喜欢
    • 2022-12-07
    • 2011-05-12
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多