mardi 5 mai 2015

SQL Server triggers - Update one field one time once another isn't null

I'm fairly new to triggers and I'm trying to update Field1 if it's null with the value from Field2 as long as Field2 isn't null on an update or insert. In other words, I want to retain the first non null value from "NonAccrual" and store it in "OriginalNonAccrual". Once OriginalNonAccrual gets a value, it should remain the same indefinitely even if NonAccrual changes. I don't know if one trigger can handle both an insert and an update and hopefully the code below gives you the idea of what I'm trying to do. Thank you!

CREATE TRIGGER tr_SAG_Accrual
ON [dbo].[SAG]
AFTER INSERT, UPDATE
AS
BEGIN
    Declare @NonAccrual date
    Declare @OriginalNonAccrual date

    Select @NonAccrual = NONACCRUAL_DATE
         , @OriginalNonAccrual = OriginalNonAccrualDate 
    from inserted

    IF @OriginalNonAccrual IS NULL AND NOT @NonAccrual IS NULL
        SET @OriginalNonAccrual = @NonAccrual
END

Aucun commentaire:

Enregistrer un commentaire