Trigger to fire only if a condition is met in SQL Server

后端 未结 7 904
夕颜
夕颜 2020-12-03 07:14

I hope this is a simple enough question for any SQL people out there...

We have a table which hold system configuration data, and this is tied to a history table via

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 07:38

    CREATE TRIGGER
        [dbo].[SystemParameterInsertUpdate]
    ON 
        [dbo].[SystemParameter]
    FOR INSERT, UPDATE 
    AS
      BEGIN
        SET NOCOUNT ON 
    
        DECLARE @StartRow int
        DECLARE @EndRow int
        DECLARE @CurrentRow int
    
        SET @StartRow = 1
        SET @EndRow = (SELECT count(*) FROM inserted)
        SET @CurrentRow = @StartRow
    
        WHILE @CurrentRow <= @EndRow BEGIN
    
            IF (SELECT Attribute FROM (SELECT ROW_NUMBER() OVER (ORDER BY Attribute ASC) AS 'RowNum', Attribute FROM inserted) AS INS WHERE RowNum = @CurrentRow) LIKE 'NoHist_%' BEGIN
    
                INSERT INTO SystemParameterHistory(
                    Attribute,
                    ParameterValue,
                    ParameterDescription,
                    ChangeDate)
                SELECT
                    I.Attribute,
                    I.ParameterValue,
                    I.ParameterDescription,
                    I.ChangeDate
                FROM
                    (SELECT Attribute, ParameterValue, ParameterDescription, ChangeDate FROM (
                                                                                                SELECT ROW_NUMBER() OVER (ORDER BY Attribute ASC) AS 'RowNum', * 
                                                                                                FROM inserted)
                                                                                        AS I 
                WHERE RowNum = @CurrentRow
    
            END --END IF
    
        SET @CurrentRow = @CurrentRow + 1
    
        END --END WHILE
    END --END TRIGGER
    

提交回复
热议问题