Solved

Trigger and xp_cmdshell

Posted on 2001-06-04
6
1,526 Views
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:
CREATE TRIGGER TR_Inquiry_u
  ON Inquiry
  FOR UPDATE
  AS
  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
    END
  END
GO

...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
0
Comment
Question by:DanRollins
  • 4
  • 2
6 Comments
 
LVL 18

Accepted Solution

by:
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.
0
 
LVL 49

Author Comment

by:DanRollins
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
0
 
LVL 18

Expert Comment

by:nigelrivett
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

as
declare @cmd varchar(1000) ,
@id int
while 1 = 0
begin
  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
    endif
  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
end
go

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.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 18

Expert Comment

by:nigelrivett
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).
0
 
LVL 49

Author Comment

by:DanRollins
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:

CREATE TRIGGER TR_Inquiry_u
  ON INQUIRY
  FOR UPDATE
  AS
  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
      END
    END
  END
GO

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
0
 
LVL 18

Expert Comment

by:nigelrivett
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.

0

Featured Post

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.

Join & Write a Comment

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.

746 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now