tags:

views:

83

answers:

2

I have created a table like this:

CREATE TABLE A
( ID BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY (
START WITH +1
INCREMENT BY +1
NO MINVALUE
NO MAXVALUE
NO CYCLE
CACHE 20
NO ORDER )
, ID_MIRROR CHAR(20))

I would like to do an insert such that ID would be automatically set, and ID_MIRROR would be what is in ID, but prefixed with 'PRE'.

I have unsuccessfully tried the following:

INSERT INTO A (ID_MIRROR) 
VALUES ( 'PRE' || CHAR(A.ID))

Error 12/4/2009 6:43:08 AM 0:00:00.296 DB2 Database Error: ERROR [42703] [IBM][DB2/AIX64] SQL0206N "A.ID" is not valid in the context where it is used. SQLSTATE=42703 1 0

insert into A (id_mirror)
VALUES (CONCAT('PRE', CHAR(identity_val_local())))

ID_MIRROR is NULL, subsequent inserts are previous value of ID.

insert into A (id_mirror)
VALUES (CONCAT('PRE', CHAR(scope_identity())))

Error 12/4/2009 6:11:11 AM 0:00:00.234 DB2 Database Error: ERROR [42884] [IBM][DB2/AIX64] SQL0440N No authorized routine named "SCOPE_IDENTITY" of type "FUNCTION" having compatible arguments was found. SQLSTATE=42884 1 0

A: 

Another forum answered the question like this:

INSERT INTO A (ID_MIRROR) VALUES ( 'PRE' || IDENTITY_VAL_LOCAL());
Michael Potter
A: 

Why would you ever need to do this when you could simply create this column on an ad hoc basis any time you wanted to, in a SELECT statement?

Tim
Tim, There at least two reasons:
Michael Potter
1) The existing rows in ID_MIRROR do not match the same pattern so they can not be recreated on SELECT. 2) The ID_MIRROR column would stay the same even after a load of the data into a new table. [db2 load has options that would reset the ID]
Michael Potter
If for some reason you wanted to maintain a history of autogenerated IDs (though I cannot think of any good design that would require this) and if reloading the table autogenerates new ids, and if there's the possibility of reloading data more than once (which there is) then a single mirror column is inadequate to the task. You'd need an external table in a many-to-one relationship to the base table. You could use an after-insert trigger on the base table to insert the auto-id into the id-archive table.
Tim
I don't understand your first sentence about "existing rows in ID_MIRROR do not match the same pattern". ID_MIRROR doesn't contain rows, but the auto-id with a prefixed string. Are you saying that the prefix changes sometimes?
Tim