2010-03-24 90 views
3

我有2个存储过程usp_SP1和usp_SP2。它们都使用插入#tt exec sp_somesp。我想创建一个第三存储过程,它将决定哪个存储过程要调用。喜欢的东西:嵌套插入exec工作

create proc usp_Decision 
(
    @value int 
) 
as 
begin 
    if (@value = 1) 
    exec usp_SP1 -- this proc already has insert into #tt exec usp_somestoredproc 
    else 
     exec usp_SP2 -- this proc too has insert into #tt exec usp_somestoredproc 
end 

后来,我意识到我需要从usp_Decision的返回值定义的,这样我可以填充SSRS数据集领域的一些结构。因此,这里是我的尝试:

  1. 在usp_Decision创建一个临时表,并做“插入#tt EXEC usp_SP1”。这没有奏效。错误“插入exec不能嵌套”

  2. 在usp_Decision中试图将表变量传递给每个存储过程,并更新存储过程中的表并执行“select * from”。那也没有成功。作为参数传递的表变量不能在存储过程中修改。

请建议可以做些什么。

+0

INSERT EXEC的破碎是我对SQL Server最大的宠儿之一。请投票! https://connect.microsoft.com/SQLServer/feedback/details/294571/improve-insert-exec – 2011-12-24 02:52:36

回答

0

在任何情况下都不是全球临时表的粉丝(其他进程可以读取这些表并可能干扰其中的数据)。

为什么不让每个proc使用本地临时表,并从该表中选择*作为最后一步。 然后你可以插入调用过程中的本地临时表。

esimple例如

create proc usp_mytest1 
as 
select top 1 id into #test1 
from MYDATABASE..MYTABLE (nolock) 

select * from #test1 
go 
--drop table #test 
create proc usp_mytest2 
as 
select top 10 MYTABLE_id into #test2 
from MYDATABASE..MYTABLE (nolock) 

select * from #test2 
go 

create proc usp_mytest3 (@myvalue int) 
as 
create table #test3 (MYTABLE_id int) 
if @myvalue = 1 
Begin 
insert #test3 
exec ap2work..usp_mytest1 
end 
else 
begin 
insert #test3 
exec ap2work..usp_mytest2 
end 

select * from #test3 

go 

exec ap2work..usp_mytest3 1 

exec ap2work..usp_mytest3 0 
+0

我在每个存储过程中使用本地临时表,因此“插入到#tt exec usp_somestored过程”。现在我想要从usp_Decision存储过程中的#tt_example中执行select *我将不得不首先插入到#tt_example exec usp_SP1中。但这是不允许的。 我不确定这是否是您建议的方法。如果没有,请解释一些伪代码。 – stackoverflowuser 2010-03-24 21:17:31

+0

我在我的存储过程中使用#tt exec sp_executesql @query 插入,因此上述方法将无法工作。 – stackoverflowuser 2010-03-25 17:10:08

+0

现在我已经justed将两个存储过程合并为一个。它是一个巨大的,但现在工作。 – stackoverflowuser 2010-03-25 17:10:26

0

你有没有看看表值用户定义函数(内联或多语句)?与HLGEM的建议类似,这将返回一个您可能不需要在任何地方插入的集合。

0

看到这个blog article一个wortkaround(使用OPENROWSET基本上建立在其上的INSERT EXEC呼叫中的一个发生在一个回环连接)

1

可以修改usp_SP1和usp_SP2?

如果是这样,在usp_Decision,创建一个本地临时表具有正确模式插入的结果:

create table #results (....) 

然后,在被调用过程,测试该临时表的存在。如果存在,请插入临时表。如果不是,像往常一样返回结果集。这有助于保留现有行为,如果从别处调用嵌套过程。

if object_id('tempdb..#results') is not null begin 
    insert #results (....) 
    select ..... 
end 
else begin 
    select .... 
end 

当控制返回到调用过程,#results将已经被嵌套PROC,哪一个被称为填充。

如果结果集不共享相同的模式,则可能需要在usp_Decision中创建两个临时表。