在存储过程中执行存储过程

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

EXEC SP1 BEGIN EXEC SP2 END 

但是我只希望SP1SP2完成运行后完成,所以我需要find一种方法让SP1SP1结束之前等待SP2完成。

SP2正在作为SP1一部分执行,所以我有这样的东西:

 CREATE PROCEDURE SP1 AS BEGIN EXECUTE SP2 END 

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

 CREATE PROCEDURE SP1 AS EXEC SP2 PRINT 'Done' 

下面是一个存储过程的例子,它执行其中的多个存储过程:

 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) 

内联我们根据需要使用的存储过程。 像不同值的示例我们必须在查询中使用不同的值。

 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 

多数民众赞成它是如何工作存储过程顺序运行,你不需要开始就像

 exec dbo.sp1 exec dbo.sp2 

您的SP2可能没有运行,因为在SP1的早期代码中出现了一些故障,所以没有达到EXEC SP2。

请发布您的整个代码。

嗨,我发现我的问题是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