Results 1 to 4 of 4
  1. #1
    Join Date
    Sep 2004
    Posts
    7

    Unanswered: put inserted value into a parameter in a trigger

    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')
    go

  2. #2
    Join Date
    Feb 2004
    Location
    In front of the computer
    Posts
    15,579
    Provided Answers: 54
    Based 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

  3. #3
    Join Date
    Sep 2004
    Posts
    7
    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.

  4. #4
    Join Date
    Feb 2004
    Location
    In front of the computer
    Posts
    15,579
    Provided Answers: 54
    To allow for multiple row inserts, you'd do something like:
    Code:
    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')
    GO
    This 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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •