سؤال

I am working on a function that needs to call a stored procedure that returns N rows and then inserts the result into a temporary table as part of its processing.

Calling the EXEC on the stored procedure works just fine: http://sqlfiddle.com/#!3/ed11a/16

So why does inserting the results of the EXEC into a table variable throw an error: http://sqlfiddle.com/#!3/ed11a/18

The error I'm getting is: Invalid use of side-effecting or time-dependent operator in 'INSERT EXEC' within a function.

I understand that this error is usually generated when trying to manipulate values that are not local to the function, but the insert is on a table variable, so this shouldn't be an issue.

هل كانت مفيدة؟

المحلول

While you are only inserting to the table variable, there is no guarantee that the stored procedure you are calling won't have side effects. There would be no way to prevent the stored procedure called from the function from inserting/updating/deleting arbitrary data, or even modifying schema. You could probably achieve what you are trying to do with a table valued function rather than a stored procedure call.

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top