I developed a small application for my office, in this application I used a trigger to read data from a web service, then update the table after the record is inserted.
Everything was working fine, except... the web service sometimes takes time to come with the result, what keeps the user waits for a long time before he gets a confirmation that the record was saved.
I thought about an asynchronous trigger, I did some google, and found that asynchronous triggers can be done with Sql Server's Service Broker, little bit from here and there, I built the following as a template for my asynchronous triggers:
USE
GO
-- Check if database exists and drop it
IF
DROP DATABASE AsyncTrigger
-- Create the database
CREATE
-- Enable Service Broker
ALTER
SET
-- Create our test table
[id] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
[Col1] [int] NOT NULL,
[Col2] [int] NOT NULL,
[Sum] [int] NULL)
-- This procedure will run asynchronously and execute our task
AS
BEGIN
DECLARE
RECEIVE
@Handle = conversation_handle,
@MessageType = message_type_name,
@Message = message_body
FROM
insert
Table1.Column1.value('@ID', 'INT') as id,
Table1.Column1.value('@Col1', 'INT')as col1,
Table1.Column1.value('@Col2', 'INT') as col2,
Table1.Column1.value('@Sum', 'INT') as [sum]
Update
from
on
END
-- Create Message Type
-- Create Contract
-- Create Queue
(
PROCEDURE_NAME = usp_Processor,
EXECUTE
-- Create Service
-- This trigger will send our message to the queue
set
TO
ON
WITH
SEND
MESSAGE
Now execute the following:
Insert
Select
Waitfor
The result will be:
id Col1 Col2 Sum----------- ----------- ----------- -----------1 34 78 NULL
id Col1 Col2 Sum----------- ----------- ----------- -----------1 34 78 112
Remember Me
a@href@title, strike
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.