Execute a stored procedure from a windows form asynchronously and then disconnect?

前端 未结 8 1280
青春惊慌失措
青春惊慌失措 2020-12-08 10:48

I am calling a stored procedure from my application that can take 30 minutes to execute.

I don\'t want to make my user leave the application open for that entire tim

相关标签:
8条回答
  • 2020-12-08 11:45

    This is actually a quite common scenario. You cannot do anything client based because the client may go away and disconnect and you'll lose the work achieved so far. The solution is to use Service Broker Activation: you create a service in the database and attach an activated procedure. In your application (or ASP page) you send a message to the service and embed the necessary parameters for your procedure. After your application commits, the message activates the service procedure. the service procedure reads the parameters from the message and invokes your procedure. since activation happens on a server thread unrelated to your original connection, this is reliable. In fact the server can even shutdown and restart while your procedure is being executed and the work will be rolled back then resumed, since the activating message will trigger again the service procedure after the restart.

    Update

    I have published the details of how to do this including sample code on my blog: Asynchronous procedure execution.

    0 讨论(0)
  • 2020-12-08 11:45

    If you really want to close down your application completely, I suggest you define a job in SQL Server Agent, and just execute a T-SQL statement to start that job manually. The syntax is:

    sp_start_job 
         {   [@job_name =] 'job_name'
           | [@job_id =] job_id }
         [ , [@error_flag =] error_flag]
         [ , [@server_name =] 'server_name']
         [ , [@step_name =] 'step_name']
         [ , [@output_flag =] output_flag]
    

    The job would execute your stored procedure. You will have to be a little creative to pass in any arguments. For example, insert the parameters into a "queue" table and have the job process all the rows in the queue.

    Instead of a job, an insert trigger on your queue should work as well.

    0 讨论(0)
提交回复
热议问题