Go Premium for a chance to win a PS4. Enter to Win


Trigger and xp_cmdshell

Posted on 2001-06-04
Medium Priority
Last Modified: 2012-05-04
I have a trigger to detect when a certain column is updated to become a certain value.  When triggered, I need to run an external program.  

A sequence like:
  ON Inquiry
  IF UPDATE( nInqStatus ) BEGIN
    IF ( SELECT nInqStatus FROM inserted ) = 7 /* QS_Rcvd*/ BEGIN
      DECLARE @sCmd varchar(256)
      SET @sCmd= 'echo>c:\temp\test.txt HI there!'
      EXEC master..xp_cmdshell @sCmd, no_output

...works just fine, but I don't need to run the echo command.  I need to run a program that will open and access the database and it must access the trigger table.  That table is locked -- presumably because the trigger is still active.

Is the xp_cmdshell the right way to run an external program?  Is there a better way?

Is there a way to make the external command run asynchronously, or to end the trigger's lock, or something -- so that the external program can access the trigger table?  If so, please describe in detail.

-- Dan
Question by:DanRollins
  • 4
  • 2
LVL 18

Accepted Solution

nigelrivett earned 800 total points
ID: 6152081
You cannot end the triggers lock - every sql statement is atomic so the trigger must run inside a transaction.

You could try crating a bound connection for the app but that sounds like getting too cmoplicated.

Easiest way is proably to put the call to the exe into a table and end the trigger (triggers should be short for the reasons you have found).
Then have a scheduled task that runs an SP that looks at this table and executes any commands in it. You can schedule the SP up to 1 min intervals - if you need it to run more quickly then schedule an SP with a delay statement in a loop that always runs.
LVL 49

Author Comment

ID: 6154072
Thanks nigelrivett,
Do you suggest perhaps, making a new table, say CmdQueue,  and in my TR_Inquiry_u, insert the command into CmdQueue?  Then periodically run the commands I have queued?

I was hoping for something a bit more realtime.  Could you show me what a continuously-running SP would look like and how to start it?  Are there performance considerations?

How about if I put an INSERT trigger on this hypothetical CmdQueue table?  Would that trigger be executed while still in the TR_Inquiry_u trigger?  Would the Inquiry table continue to be locked if I ran xp_cmdshell from this CmdQueue trigger?

-- Dan
LVL 18

Expert Comment

ID: 6155435
The inquiry table would still be locked as the sql statement would not complete until all triggers have completed - the server will roll back everything if there is a failure so it has to lock everything until returning from the statement.

You could do an sp_startjob in the trigger which would be fairly real time.

You could set the continuously running sp to start on server startup or just schedule it to to run every 5 mins or so - this means that if it aborts it will get restarted.

sp looks smething like

declare @cmd varchar(1000) ,
@id int
while 1 = 0
  select @id = null
  while @id is null
    select @id = min(id) from cmdtbl where status = 0
    if @id is null
       waitfor delay '00:00:05'  -- wait 5 secs
  select @cmd = cmd from cmdtbl where id = @id
  update cmdtbl set status = 1 where id = @id -- in process
  exec (@cmd)
  update cmdtbl set status = 2 where id = @id -- complete

You might want to hold the max id and wait for another one rather than use the status in case this table gets large and needs an index - otherwise have a daily archive job running to keep the table small.
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

LVL 18

Expert Comment

ID: 6155446
NB you might want to check how long it takes a start job to take effect before using it and what happens if it executes between the job completing and getting back in the queue - it takes a long time for complete jobs to reschedule in v7 it appears.

Also with the startjob yuo will still need the loop in case another job comes along before the first completes - you could in fact have several jobs so that several commands could be executed at the same time if you are brave (hence the in process status).
LVL 49

Author Comment

ID: 6158242
I tried a few tests with sp_start_job and never hd any success at all.  Either the command is not running or is waiting a long time to start or something else.  I didn't get any error messages, just no joy:

  IF UPDATE( nInqStatus ) BEGIN
    IF ( SELECT nInqStatus FROM inserted ) = 7  BEGIN  
      DECLARE @sCmd varchar(256), @sInqIdx varchar(10), @sJobName varchar(256)
      SELECT @sInqIdx= nInqIdx FROM inserted
      SET @sCmd= 'echo>c:\mce\sCmd.txt HI THERE'

      -- create a one-step, one-shot job
      SET @sJobName= 'RptGen_' + @sInqIdx

      IF NOT EXISTS (SELECT name FROM msdb.dbo.sysjobs WHERE name= @sJobName ) BEGIN
        EXEC msdb.dbo.sp_add_job @job_name= @sJobName,
           @enabled= 0,       /* exec only on request */
           @delete_level= 3,  /* delete when done */
           @description= 'Runs RptGen',
           @owner_login_name= 'SA'
        EXEC msdb.dbo.sp_add_jobstep @job_name= @sJobName,
           @step_id= 1,
           @step_name= 'gen rpt',
           @subsystem= 'CMDEXEC',
           @command= @sCmd
        EXEC msdb.dbo.sp_start_job @job_name= @sJobName

Even when I do it ad-hoc (not in the trigger), I'm getting no joy.  I suppose that I need to have the SQL Server Agent running (and I did in several tests, with no obvious success -- sCmd.txt was not created).   Where is the success/failure/error code of these jobs recorded?

Anyway, if I need to have the Server Agent running, it sort of defeats my purpose: I *already* have a separate process polling for changes and doing the work.  I was looking for an "A happened, so do B" sort of solution.

I have not tried implementing the CmdQueue idea so that is next. I always hesitate before adding a new table and its associated potential maintenance.    

Damn, this is turning out to be a pain.  I'll keep trying different things as I get time.  If you have any more tips to help keep my head above water, I'll appreciate them.

-- Dan
LVL 18

Expert Comment

ID: 6161921
You need to have the agent running to start any jobs.

You need to add a server to the job to get it to run I think.


Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Ready to get certified? Check out some courses that help you prepare for third-party exams.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question