on 2015 Dec 18 10:23 AM
If I have a trigger defined to fire "BEFORE INSERT,UPDATE", is there a way to determine whether the event is question is an INSERT or UPDATE? The table involved has at least one field defined as "not null", so at first blush I'm tempted to use something like this:
CREATE TRIGGER MyTrigger BEFORE insert, update on MyTable
referenceing old as OldRec new as NewRec
for each row
begin
declare isInsert char(3);
if OldRec.RequiredField is null then
isInsert = 'Yes';
else
isInsert = 'No';
end if
end
I've looked to see if there is a built-in variable I can reference to make the determination, but my searching powers are apparently too weak. We are using SQL/Anywhere 16.
Request clarification before answering.
Yes, you can use the "Trigger operation conditions" to tell an INSERT from an UPDATE.
More on this is also discussed in that other FAQ.
Note that your proposed code won't work: There's no OLD row to check in an INSERT statement - IMHO, the operation will fail, and so will the INSERT, either.
If you simply want to fill a NOT NULL column with a value, you simply can do so in a BEFORE INSERT trigger, as the NOT NULL check will be done later, so you simply might use:
if NewRec.RequiredField is null then
set NewRec.RequiredField = <whatever>;
end if;
FWIW, here's an old posting by Glenn Paulley with detailed insights (as expected...) on the internal steps a trigger has to consider - cf. that old NNTP article "Before update trigger and computed column " - I'm not sure whether it is fully true for current versions, however, a BEFORE TRIGGER surely is run before NULLs in NOT NULL columns are checked.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
87 | |
9 | |
9 | |
8 | |
6 | |
6 | |
6 | |
5 | |
5 | |
4 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.