David David - 3 years ago 148
reST (reStructuredText) Question

How to call restful service from SQL Server trigger

I need to call a restful web service with a single parameter from the insert event in a SQL Server database table. I know this is not ideal design but I don't have control of either end point. The usage of this functionality will not exceed 100 events/min at max load.

I'm open to other ideas but the two options I came up with were;


  1. insert trigger - service broker - .NET windows service to call web service

  2. C# CLR trigger to call restful service directly



I have been working on option 2 and created a SQL CLR trigger project in Visual Studio but after I add the references to
System.Web
the project will not build and there are no build errors, vs just says "build failed" in the output window.

Is there some restriction about which CLR libraries can be used in a CLR trigger?

Using the service broker scares me since I have only worked on one project with the service broker and found it very difficult to implement.

Any ideas on how to call the web service from the trigger event would be greatly appreciated.

David

Answer Source

A trigger is run in the context and scope of the statement that causes it to fire - this means, that statement isn't going to complete until the trigger is completely run.

A trigger should be very nimble - small and fast. You should never ever call external services from a trigger, you should not include cursors in triggers, you should not do any heavy lifting or lengthy calculations in a trigger.

If you really must do something like this, I'd recommend an approach that:

  • see the trigger just put a few values into a "Command" table - those values that the long-running process will need to complete its work

  • have a de-coupled, separate process (e.g. a stored procedure or something) that will check that "Command" table periodically for new tasks to complete - this can be done in SQL Server using a SQL Server Agent Job

  • the decoupled process then grabs the information from the "Command" table, does it's work, and updates the database (if necessary)

This way, your trigger is small and nimble and completes quickly, thus not slowing down your main process / main system. The lengthy process is decoupled, standalone, and can be implemented in whichever way makes most sense (stored procedure inside SQL Server, or a separate standalone e.g. command-line tool or whatever makes sense).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download