2008-10-04 158 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