2008-10-04 156 views
37

我想在存储过程中执行存储过程,例如,在存储过程中执行存储过程

EXEC SP1 

BEGIN 

EXEC SP2 
END 

但我只想SP1SP2运行完毕后才能完成,所以我需要找到SP1一种方式来等待SP2之前SP1端完成。

SP2被作为SP1一部分执行的,所以我有这样的:

CREATE PROCEDURE SP1 
AS 
BEGIN 

EXECUTE SP2 

END 
+0

标签微调 - “服务器”造成了一定的误报 – finnw 2008-10-04 13:55:03

+0

嗨,重新标记。我们正在合理化mssql和sqlserver标签。 – ConcernedOfTunbridgeWells 2008-10-08 15:16:54

+2

看起来像这个问题是一个[重复](http://stackoverflow.com/questions/170440/stored-procedure-not-being-executed-within-another-stored-procedure)。请只问你一个问题。 – Rick 2008-10-13 01:02:34

回答

3

这就是它的工作原理如何存储过程才能运行,你不需要开始只是像

exec dbo.sp1 
exec dbo.sp2 
11

下面是我们其中一个执行其中多个存储过程的示例:

ALTER PROCEDURE [dbo].[AssetLibrary_AssetDelete] 
(
    @AssetID AS uniqueidentifier 
) 
AS 

SET NOCOUNT ON 

SET TRANSACTION ISOLATION LEVEL READ COMMITTED 

EXEC AssetLibrary_AssetDeleteAttributes @AssetID 
EXEC AssetLibrary_AssetDeleteComponents @AssetID 
EXEC AssetLibrary_AssetDeleteAgreements @AssetID 
EXEC AssetLibrary_AssetDeleteMaintenance @AssetID 

DELETE FROM 
    AssetLibrary_Asset 
WHERE 
    AssetLibrary_Asset.AssetID = @AssetID 

RETURN (@@ERROR) 
32

T-SQL不是异步的,所以你真的别无选择,只能等到SP2结束。幸运的是,这就是你想要的。

CREATE PROCEDURE SP1 AS 
    EXEC SP2 
    PRINT 'Done' 
1

嗨我发现我的问题是SP2执行SP1时不从SP1内执行。

下面是SP1的结构:

ALTER PROCEDURE SP1 
AS 
BEGIN 

Declare c1 cursor.... 

open c1 
fetch next from c1 ... 

while @@fetch_status = 0 
Begin 

... 

Fetch Next from c1 
end 

close c1 

deallocate c1 

exec sp2 

end 
1

你的SP2可能是不是因为在SP1早期代码的一些故障,从而未达到EXEC SP2上运行。

请发布您的整个代码。

9

内联我们根据需要使用的存储过程。 例子就像我们在查询中使用不同的值不同的相同的参数..

Create Proc SP1 
(
@ID int, 
@Name varchar(40) 
-- etc parameter list, If you don't have any parameter then no need to pass. 
) 

    AS 
    BEGIN 

    -- Here we have some opereations 

-- If there is any Error Before Executing SP2 then SP will stop executing. 

    Exec SP2 @ID,@Name,@SomeID OUTPUT 

-- ,etc some other parameter also we can use OutPut parameters like 

-- @SomeID is useful for some other operations for condition checking insertion etc. 

-- If you have any Error in you SP2 then also it will stop executing. 

-- If you want to do any other operation after executing SP2 that we can do here. 

END