Tuesday, June 26, 2012

DEFAULT CLAUSE DOES NOT SUPPORT USER DEFINED FUNCTION in DB2

In DB2 , DEFAULT Clause does not support any user defined function.

Solution would be to define a Before/After trigger (depending upon requirement).
A)    If the requirement is to call the function whenever there is no value provided for that particular column - Then we should go for After trigger.
B)    If the requirement is to call the function every time an insertion happens :- We should go for Before trigger.


SOURCE CODE - EXAMPLE:   

db2 "alter table tabs alter column c2 set with default SYS_GUID()"
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0574N DEFAULT value or IDENTITY attribute value is not valid for column
"C2" in table "ADMINISTRATOR.TABS". Reason code: "7". SQLSTATE=42894

SOLUTION :


A) After trigger :
db2 "create or replace trigger t1 after insert on tabs REFERENCING NEW AS n
FOR EACH ROW BEGIN ATOMIC IF n.C2 is null then update tabs SET C2 = SYS_GUID(); END IF ; END"

B)Before trigger :
db2 "create or replace trigger t1 before insert on tabs REFERENCING NEW AS n FOR EACH ROW SET n.ID = SYS_GUID()"

1 comment:

  1. Nice blog !! Thanks dude . It really helped.

    ReplyDelete