问题
I have two example tables:
TABLE1:
ID | COLUMN_B| COLUMN_C
_________|_________|_________
1 | 0 | 1
________|_________|_________
2 | 0 | 1
________|_________|_________
3 | 0 | 1
TABLE2:
ID | COLUMN_E| COLUMN_F
________|_________|________
1 | Y | X
________|_________|_________
2 | Y | X
________|_________|_________
3 | Y | X
What I would like to do is to write a trigger on Hana Studio using SQL Script to update column E from table 2 when column B from table 1 is updated to a specific value (let's say, 100). Rows from table 1 are referenced in table 2 with the first column (ID).
I wrote the following code:
create trigger "UPDATE_TABLES"
after update of "COLUMN_B" on "TABLE1"
referencing new row as new, old row as old
for each row
begin
update "TABLE2"
set "COLUMN_E" = 'my new value'
where :old."COLUMN_B" = '100' and "TABLE1"."ID" = :old."ID";
end;
When I set TABLE1.COLUMN_B on row 1 to 100, I expect the code to change TABLE2.COLUMN_E to "my new value" on row 1, but nothing happens. Could anyone point what exactly I am doing wrong here?
回答1:
I guess the UPDATE statement in the trigger code should be slighly different as follows
create trigger "UPDATE_TABLES"
after update of "COLUMN_B" on "TABLE1"
referencing new row as new, old row as old
for each row
begin
update "TABLE2"
set "COLUMN_E" = 'my new value'
where :new."COLUMN_B" = '100'
and TABLE2.ID = :old."ID";
end;
Otherwise, I get syntax error while creating the trigger Could you please verify?
回答2:
Rookie mistake. I wanted the column_e value to change on changes on values from column_b, but I was actually tracking the old values from column_b. Corrected it to:
create trigger "UPDATE_TABLES"
after update of "COLUMN_B" on "TABLE1"
referencing new row as new, old row as old
for each row
begin
update "TABLE2"
set "COLUMN_E" = 'my new value'
where :new."COLUMN_B" = '100' and "TABLE1"."ID" = :old."ID";
end;
and it worked!
来源:https://stackoverflow.com/questions/52297810/conditional-update-on-hana-studio-sql-script-trigger