Home > other >  Create a trigger for a table that fills a column in the same table whenever a new record is inserted
Create a trigger for a table that fills a column in the same table whenever a new record is inserted

Time:12-10

I have a table called HiringEMP which has data related to recruiting and there is a column called HiringStage with 9 possible values:

1 - Candidate Declined
4 - Conversation On Hold
7 - Contract Out
2 - Target
3 - Initial Conversations
8 - Hired
0 - Not A Fit
6 - Offer Stage
5 - Advanced Conversations

My job is to create a conversation_date column in the HiringEMP table and the value should be automatically populated via a table trigger when the HiringStage column is at a level 3 or higher.

The value should be the current timestamp at the time the stage changed at or above 3. Once the date is initially set the value should no longer change even if the status changes again from 3 to any of the above values.

What I was able to do so far is.

I have created a trigger which populates the conversation_date column with current timestamp when the data is inserted and the value is 3 or greater or when the data is updated to anything above 1 and 2. But the problem is my trigger updates the conversation_date anytime the field is updated I want it to only update once for example if I insert a new row with the hiring stage as 3 - Initial Conversations it will add the current_timestamp to the conversation_date column, but when I update the same row to 4 - Conversation On Hold or 5 - Advanced Conversations it should still have the same timestamp that was when the row was initially added.

CREATE TRIGGER trg_convodate
ON [dbo].[HiringEMP]
FOR INSERT, UPDATE 
AS
BEGIN
    SET NOCOUNT ON

    IF (LEFT((SELECT HiringStage FROM INSERTED), 4) <> '0 - 'AND LEFT((SELECT HiringStage FROM INSERTED), 4) <> '1 - ' AND LEFT((SELECT HiringStage FROM INSERTED), 4) <> '2 - ')
    BEGIN
        UPDATE [dbo].[HiringEMP]
        SET conversation_date = CURRENT_TIMESTAMP
        WHERE id IN (SELECT DISTINCT id FROM inserted)
    END
END

Please provide an example regarding the changes required to my query.

CodePudding user response:

The following should do what you require. Comments explain the logic.

CREATE TRIGGER dbo.g_convodate
ON dbo.HiringEMP
FOR INSERT, UPDATE 
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE dbo.HiringEMP SET
        conversation_date = CURRENT_TIMESTAMP
    -- Filter to only records in the update/insert
    WHERE id IN (SELECT id FROM Inserted)
    -- Filter to HiringStage >= 3
    -- This assumes that you only ever have a single digit at the first character
    -- If that ever changes it will break badly
    -- Ideally you would store the stage as FK reference to another table with a numeric value and a description
    AND CONVERT(int, LEFT(HiringStage,1)) >= 3
    -- Only update if its not already set
    AND conversation_date IS NULL;
END;
  • Related