利用Sql作业在asp.net 里面实现异步调用存储过程.

   
       因为asp.net的bs 机制 ,我们长期在执行一个比较复杂,超做时间比较长的存储过程的时候,页面超时,停止响应.使用这个方法可以通过sql 作业 实现程序的异步调用的临时Job

/******************************************************************************
* 在SQL SERVER 2000中创建用于执行异步调用的临时Job
* @EXECSQL: Transact-SQL batch
* Eample: EXEC dbo.AsynchronousInvoking @EXECSQL = 'UPDTAE customer SET balance = 0'
* 缺点:该存储过程必须指定数据库的名字
******************************************************************************/
CREATE Procedure bak
@EXECSQL nvarchar(4000),
@job nvarchar(50),
@servern nvarchar(50),
@dbname nvarchar(50)
AS

BEGIN TRANSACTION
DECLARE @JobID BINARY(16)
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0

BEGIN

-- Add the job
EXECUTE @ReturnCode = msdb.dbo.sp_add_job @job_id = @JobID OUTPUT ,
@job_name = @job,
@owner_login_name = N'',
@description = N'description for job', -- the description of the job
@category_name = N'[Uncategorized (Local)]', 
@enabled = 1,
@notify_level_email = 0,
@notify_level_page = 0,
@notify_level_netsend = 0,
@notify_level_eventlog = 0,
@delete_level= 3

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

-- Add the job steps
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobstep @job_id = @JobID,
@step_id = 1,
@step_name = N'step1',
@command = @EXECSQL, -- sql batch
--缺点:该存储过程必须指定数据库的名字
@database_name = @dbname, --the database name of the job to manipulate
@server = N'',
@database_user_name = N'',
@subsystem = N'TSQL',
@cmdexec_success_code = 0,
@flags = 0,
@retry_attempts = 0, --execute once only
@retry_interval = 0,
@output_file_name = N'',
@on_success_step_id = 0,
@on_success_action = 1, -- on success abort
@on_fail_step_id = 0,
@on_fail_action = 2 -- on fail abort

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

--set the star step id of the job
EXECUTE @ReturnCode = msdb.dbo.sp_update_job @job_id = @JobID,
@start_step_id = 1

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

-- Add the Target Servers
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @JobID,
@server_name = @servern--传入的服务器名称

IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

COMMIT TRANSACTION
GOTO EndSave

QuitWithRollback:
IF (@@TRANCOUNT > 0) BEGIN
ROLLBACK TRANSACTION
RETURN 1
END
EndSave:

--star the job immediately
EXEC @ReturnCode = msdb.dbo.sp_start_job @job_id = @JobID

--return to the invoker immediately
RETURN @ReturnCode

 

GO

posted on 2006-05-25 15:53  吴磊  阅读(3319)  评论(1编辑  收藏  举报