0

I have a stored procedure that returns a pair of output parameters - the ID and the computed value. Is it possible to use a trigger with an insert statement, that inserts those two values directly? Something like this

CREATE TRIGGER Trig_FirstTable ON SecondTable AFTER UPDATE
AS 
BEGIN
INSERT INTO FirstTable (OtherID, OtherValue)
VALUES (@otherID, @otherValue)
FROM StoredProcedure inserted.ID, inserted.Value, @otherID OUTPUT, @otherValue OUTPUT
END
3
  • does the stored procedure update the same data in SecondTable? Commented Apr 20, 2015 at 8:46
  • 2
    To the best of my knowledge, not the way you wrote it. You can execute the stored procedure and use the output variables to do whatever you want in the trigger, but you can't use the stored procedure in a FROM clause. Commented Apr 20, 2015 at 8:49
  • you'll have to iterate through records in inserted, then call your procedure and then insert into the FirstTable Commented Apr 20, 2015 at 8:53

2 Answers 2

1

According to the MSDN documentation you can use INSERT into with EXEC. They give the following example:

--INSERT...EXECUTE procedure example
INSERT author_sales EXECUTE get_author_sales

But I think your stored procedure needs a SELECT statement to return the data instead of only filling the output parameters.

Sign up to request clarification or add additional context in comments.

Comments

0

You can insert from SP like that:

drop procedure uspTest
GO
create procedure uspTest
AS
select 1 as id, 'x' as val
union all 
select 2,'y'
GO

drop table #temp
GO
create table #temp (
    id int, 
    val char(1) 
)
GO

insert into #temp (id,val)
EXECUTE uspTest
GO

select
    *
from #temp

But you cannot select a subset of columns, so this method will obviously fail if you add more outputs to your SP in the future:

insert into #temp (id)
EXECUTE uspTest

Another way is to store SP results in variables, and then use them for insert.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.