T-SQL中的异步存储过程调用

时间:2021-05-17 16:37:56

How one can make an async call to a stored procedure from another one?

如何从另一个存储过程进行异步调用?

Assume I have two stored procedures, SP1 and SP2 (this is a long running stored procedure, takes much time to execute, and doesn't return any result).

假设我有两个存储过程,SP1和SP2(这是一个长时间运行的存储过程,需要很长时间才能执行,并且不会返回任何结果)。

The stored procedure SP1 is defined like this:

存储过程SP1的定义如下:

CREATE PROCEDURE SP1
AS
BEGIN

  --custom business logic

  --CALL to SP2, but async

  EXEC SP2

END

How could you make a non-blocking/async call to SP like the above in SQL Server 2008/2012?

如何像SQL Server 2008/2012中的上述那样对SP进行非阻塞/异步调用?

2 个解决方案

#1


4  

There was once I tried to achieve this by wrapping the stored procedure into Job, and then Calling the job in the procedure through sp_start_job system sp.

曾经有一次我试图通过将存储过程包装到Job中来实现这一点,然后通过sp_start_job系统sp调用该过程中的作业。

EXEC dbo.sp_start_job N'Job name' ;

#2


0  

Blockquote
Works as long as there are no arguments. – RoastBeast Dec 22 '15 at 17:30

Blockquote只要没有参数就可以工作。 - RoastBeast 2015年12月22日17:30

Here's version with passing parameters

这是带有传递参数的版本

  declare @variable -- job name
declare @command -- command

set @command = 'select * from table where data='+@variable

exec msdb..sp_add_job
@job_name =@variable,
@enabled=1,
@start_step_id=1,
@delete_level=1 --Job will delete itself after success

exec msdb..sp_add_jobstep
@job_name=@variable,
@step_id=1,
@step_name='step1',
@command=@command

exec msdb..sp_add_jobserver
@job_name = @variable,
@server_name = 'yourserver'

exec msdb..sp_start_job
@job_name=@variable

#1


4  

There was once I tried to achieve this by wrapping the stored procedure into Job, and then Calling the job in the procedure through sp_start_job system sp.

曾经有一次我试图通过将存储过程包装到Job中来实现这一点,然后通过sp_start_job系统sp调用该过程中的作业。

EXEC dbo.sp_start_job N'Job name' ;

#2


0  

Blockquote
Works as long as there are no arguments. – RoastBeast Dec 22 '15 at 17:30

Blockquote只要没有参数就可以工作。 - RoastBeast 2015年12月22日17:30

Here's version with passing parameters

这是带有传递参数的版本

  declare @variable -- job name
declare @command -- command

set @command = 'select * from table where data='+@variable

exec msdb..sp_add_job
@job_name =@variable,
@enabled=1,
@start_step_id=1,
@delete_level=1 --Job will delete itself after success

exec msdb..sp_add_jobstep
@job_name=@variable,
@step_id=1,
@step_name='step1',
@command=@command

exec msdb..sp_add_jobserver
@job_name = @variable,
@server_name = 'yourserver'

exec msdb..sp_start_job
@job_name=@variable