Share via

Trigger on 1 column update

david chase 41 Reputation points
2021-12-22T16:03:23.2+00:00

I am creating a trigger on a table to run a stored proc only when a specific column is updated. Below is my trigger code but when I try to run UPDATE to that column I get "Error converting data type nvarchar to smalldatetime. The statement has been terminated." The column named OriginalTargetDate is a smalldatetime data type.

USE [Marshall]
GO

/****** Object:  Trigger [dbo].[T_RepairOrder_DTrig]    Script Date: 12/22/2021 9:34:04 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE OR ALTER TRIGGER [dbo].[T_RepairOrder_UTDDTrig] 
ON [dbo].[RepairOrder]
FOR UPDATE AS
BEGIN

    IF ( UPDATE (OriginalTargetDate) )
        BEGIN
            EXEC ms_updTDDTime OriginalTargetDate;
        END
END
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.


Answer accepted by question author

Viorel 127K Reputation points
2021-12-22T17:01:51.217+00:00

To send the new value, try something like this:

. . .
declare @d smalldatetime = (select top(1) OriginalTargetDate from inserted)
EXEC ms_updTDDTime @d
. . .

However you should probably redesign the trigger to support multiple updates (when several rows are changed).

Was this answer helpful?

0 comments No comments

2 additional answers

Sort by: Most helpful
  1. david chase 41 Reputation points
    2021-12-22T23:52:04.417+00:00

    Thanks everyone! All of your feedback helped me find a solution.

    Was this answer helpful?


  2. Tom Phillips 17,786 Reputation points
    2021-12-22T20:25:02.4+00:00

    This should get you started:
    CREATE OR ALTER TRIGGER [dbo].[T_RepairOrder_UTDDTrig]
    ON [dbo].[RepairOrder]
    FOR UPDATE AS
    BEGIN
    IF ( UPDATE (OriginalTargetDate) )
    BEGIN
    DECLARE @newdate datetime;
    DECLARE update_cursor CURSOR FOR
    SELECT DISTINCT i.OriginalTargetDate -- updated value
    FROM INSERTED i
    INNER JOIN DELETED d
    ON d.RepairOrderPK = i.RepairOrderPK
    WHERE i.OriginalTargetDate <> d.OriginalTargetDate
    OPEN update_cursor;
    FETCH NEXT FROM update_cursor INTO @newdate;
    WHILE @@Fetch _STATUS=0
    BEGIN
    EXEC ms_updTDDTime @newdate;
    FETCH NEXT FROM update_cursor INTO @newdate;
    END
    CLOSE update_cursor;
    DEALLOCATE update_cursor;
    END
    END

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.