tags:

views:

471

answers:

4

Hi

Is it possible to trigger an action in Windows Service, or is it possible to raise an event that can be caught in a Service from a stored procedure.

If you imagine a service runs every 5 minutes thats performs some action. What if something happens in a database or a stored procedure is executed and I want to trigger this action earlier than the 5 minutes.

Does anybody have any ideas?

Thanks

Ed

+1  A: 

You can create a CLR procedure in SQL Server that somehow communicates with the service using SOAP, Remoting, or whatever medium. This is generic though. I think query notification feature of SQL Server 2005 can be helpful here.

Mehrdad Afshari
I think you're right, I've just been having a read about query notifications they seem to be the correct answer to the problem I have. Thanks.
MrEdmundo
A: 

if you do a raiserror(@ErrorMessage,16,1) it should generate an exception on the client side as long as you use a severity and state of 16 and 1.

Jeremy
+2  A: 

It sounds like you shouldn't be using a windows service at all. I'd setup a SQL job to run every 5 minutes, then setup a trigger or whatever you expect to happen to run the job manually if necessary.

EDIT: However, if the service is doing something outside of the database, you can use xp_cmdshell to run system commands (not the best option though).

scottm
DTS might be a better solution than windows service.
Saif Khan
The idea of a job does not solve my problem. You still have the time issue. I want to be able to perform a specific action as a result of something within the database. I don't want to have to create a Job for each action I might want to perform.
MrEdmundo
Well, without knowing what kind of action you want to perform and on what criteria you want to perform it, I can't answer any further.
scottm
I understand what you're saying scotty but that just isn't true. Anyway somebody has pointed me in the direction of query notifications. Thanks for you help.
MrEdmundo
A: 

Following on from Mehrdad's comments, I was able to solve the problem using the SqlDependancy Class in the .NET framework.

This Class allows you to register a SQL query and connection with it, when the result of that query changes an event is raised to indicate a change in the data.

This allowed me to catch data changes almost instantaneously and deal with appropriately.

In order to use this Class you will need to Enable Query Notifications on the database you wish to query see: Enabling Query Notifications

A good example of how to use this class in a Windows Application is found here.

MrEdmundo