How would i get the value of a field that i just inserted and put that into a parameter, so that i could update another table.
This is the code that i used in the trigger that did not work:
@.field1 = select srcfield1 from inserted
Anyway here is the full code:
CREATE TABLE Source (srcID int IDENTITY, srcField1 nvarchar(50))
CREATE TABLE Destination (destID int IDENTITY, destField1 nvarchar(50))
go
CREATE TRIGGER tr_SourceInsert ON [dbo].[Source]
FOR INSERT
@.Field nvarchar(50) output
AS
SELECT @.Field1 = SELECT Field1 FROM inserted
UPDATE Destination
SET Field1 = @.Field
where destID = '1'
go
INSERT Source(srcfield1) VALUES ('A')
goBased on your sample, there are no rows in the destination table. There couldn't be anything to update.
Just FYI, you appear to be taking a "one row" approach to your trigger, This will fail the first time you insert multiple rows into the source table using a single SQL statement.
If you explain a bit more about what you are trying to do, I'd bet that someone here can help you, but I don't understand well enough to be much help yet.
-PatP|||Okay, i forgot the line of sql that inserted a row into the DESTINATION table. Here it is data in it.
INSERT Source(srcfield1) VALUES ('1')
And i got the trigger to work by changing the code to:
SELECT @.field1 = srcField1 from inserted
How would i change this to take a 'multiple row' that you refer to.
thanks.|||To allow for multiple row inserts, you'd do something like:CREATE TABLE Source (srcID int IDENTITY, srcField1 nvarchar(50))
GO
CREATE TABLE Destination (destID int IDENTITY, destField1 nvarchar(50))
go
CREATE TRIGGER tr_SourceInsert ON [dbo].[Source]
FOR INSERT AS
UPDATE d
SET d.Field1 = i.Field1
FROM inserted AS i
JOIN destination AS d
ON d.destID = '1'
RETURN
GO
INSERT Source(srcfield1) VALUES ('1')
GO
INSERT Source(srcfield1) VALUES ('A')
GOThis code still seems suspect for a trigger, since I can't fathom why you would always want to update the destination table this way. There may be a reason for it, but I'm skeptical.
-PatP
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment