为什么在UDF中使用INSERT-EXEC [存储过程]语句会产生副作用错误?

时间:2012-07-17 15:44:56

标签: sql sql-server-2005 exec user-defined-functions table-variable

我正在处理一个函数,该函数需要调用一个返回N行的存储过程,然后将结果作为其处理的一部分插入临时表中。

在存储过程上调用EXEC可以正常工作: http://sqlfiddle.com/#!3/ed11a/16

那么为什么将EXEC的结果插入表变量会引发错误: http://sqlfiddle.com/#!3/ed11a/18

我得到的错误是:Invalid use of side-effecting or time-dependent operator in 'INSERT EXEC' within a function.

我知道这个错误通常是在尝试操作非函数本地的值时产生的,但是insert是在表变量上,所以这不应该是个问题。

1 个答案:

答案 0 :(得分:3)

虽然您只是插入表变量,但无法保证您调用的存储过程不会产生副作用。没有办法阻止从函数调用的存储过程插入/更新/删除任意数据,甚至修改模式。您可以使用表值函数而不是存储过程调用来实现您尝试执行的操作。

Alter function dbo.MyTable() 
RETURNS  @table TABLE 
(
    -- columns returned by the function
    Col1 int null, 
    Col2 int null, 
    Col3 int null,
    Col4 int null,
    Col5 int null, 
    Col6 int null

)
as
Begin
INSERT INTO @table Values( null, null, 5, null, 63, null)

return 
End