Solved

Trigger and xp_cmdshell

Posted on 2001-06-04
6
1,598 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 
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

Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.

Question has a verified solution.

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

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Viewers will learn how the fundamental information of how to create a table.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

622 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