Search code examples
sqltriggershana

How to update the same table in SAP HANA Triggers


I am trying to write a trigger in SAP HANA to update a field of a table when new records are being inserted to that table. Following is a sample trigger that I have written.

CREATE TRIGGER SAMPLE
AFTER INSERT ON TARGET_TABLE
REFERENCING NEW ROW NEW_ROW
FOR EACH ROW
BEGIN
    UPDATE TARGET_TABLE SET VALID_FROM='2018-02-01' WHERE ITEM=:NEW_ROW.ITEM
END

When I try this, I get the error:

Modification of subject table in trigger not allowed

Is there a way by which I can achieve this?

This suggests to use the transition variable NEW_ROW, appreciate if a code sample can be provided.


Solution

  • You don't actually need to create trigger for your requirement as I can see from your post (of course if it is only updating a date field)

    You can define the VALID_FROM column with a DEFAULT value

    For example,

        Create Column Table DefaultColumnTable (
         Id int,
         Code varchar(5),
         VALID_FROM date default '2018-02-01'
        )
    

    So whenever a new row is inserted, unless an alternative value is stated the valid_from column will be populated with default date specified in the DDL command above.

    The users can change the valid_from field value without any problem

    @Kalpa, maybe you can use BEFORE INSERT Trigger Please check following sample

    create trigger TriggerTable_B_INS BEFORE INSERT on TriggerTable
    REFERENCING NEW ROW mynewrow
    FOR EACH ROW
    begin
    
    declare lv_d date;
    lv_d := '20180201';
    
    mynewrow.VALID_FROM = :lv_d;
    
    end;
    

    You set only the new row columns before Insert command executes over the target table. You don't explicitly execute an INSERT command, just set new values for new row columns. That's all

    I hope it helps