Trigger and xp_cmdshell

Posted on 2001-06-04
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
GO 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 200 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.
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

821 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