SQL 为什么不能在另一个存储过程调用的存储过程中使用 INSERT EXEC 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3853801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can't use INSERT EXEC statement within a stored procedure called by another stored procedure?
提问by Péter
First I try to explain the circumstances. I store the the filter expression in one column separated by line breaks. The base idea was this:
首先,我尝试解释情况。我将过滤器表达式存储在由换行符分隔的一列中。基本想法是这样的:
SELECT
'SELECT ''' + REPLACE(topic_filter,CHAR(10),''' UNION ALL SELECT ''') + ''''
FROM dbo.topic_filter T
WHERE
T.id = @id
FOR XML PATH('')
After this I simply execute this string to put the datas into a temp table.
My problem starts here.
The snippet is in a stored procedure and used by multiple stored procedures to generate the base source to fill.
Approach 1:
Call this sp from another SP to fill a temp table.
Result 1:
An INSERT EXEC statement cannot be nested.
(If I call simply with exec dbo... style the code is working. I only get the error if I try to call within a stored procedure)
在此之后,我只需执行此字符串即可将数据放入临时表中。我的问题从这里开始。该代码段位于一个存储过程中,并由多个存储过程使用以生成要填充的基本源。
方法一:
从另一个SP调用这个sp来填充一个临时表。
结果 1:
不能嵌套 INSERT EXEC 语句。(如果我只是用 exec dbo ... 样式调用代码正在工作。如果我尝试在存储过程中调用,我只会收到错误)
Approach 2:
I put the code above into a table values function.
Result 2:
Invalid use of a side-effecting operator 'INSERT EXEC' within a function.
(The function itself don't compiled)
方法二:
我把上面的代码放到一个表值函数中。
结果 2:
在函数内无效使用副作用运算符“INSERT EXEC”。(函数本身没有编译)
Thanks,
Péter
谢谢,
彼得
采纳答案by Péter
In the meantime I managed to solve the problem (with help :) ). The solution is simple:
与此同时,我设法解决了这个问题(在帮助下:))。解决方法很简单:
exec('insert into t2 ' + @str)
Where @str contains a select statement.
I don't know why but this way there is no error. The method I call the stored procedure:
其中@str 包含一个选择语句。
我不知道为什么,但这样就没有错误了。我调用存储过程的方法:
SET @exec = 'exec dbo.trFilterTopic ''' + @id+ ''',null,null,1'
INSERT INTO #filtered
exec (@exec)
I hope I spare some time to other folks with this solution.
Bye,
Péter
我希望我能抽出一些时间给其他人使用这个解决方案。
再见,
彼得
回答by GSerg
It is an SQL Server restriction. You cannot have a nested insert exec
(I'm not sure why).
这是 SQL Server 限制。你不能有一个嵌套insert exec
(我不知道为什么)。
If you go:
如果你走的话:
insert into t(value)
exec dbo.proc
, and inside dbo.proc
you have
,在dbo.proc
你里面你有
insert into t2(value2)
exec(@str)
, then it will not run.
,那么它就不会运行。
Consider different ways of passing tables around, such as temporary tablesor table-valued parameters.
回答by fausto
Functions on SQL Server have limitations, they arenot procedures, you can't use dynamic SQL like 'EXECUTE STRING', 'INSERT EXEC'...
SQL Server 上的函数有局限性,它们不是过程,您不能使用像“EXECUTE STRING”、“INSERT EXEC”这样的动态 SQL...