简体   繁体   中英

how to use the value of an Identity column for a diffent column in the same insert

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

另一个论坛回答了这样的问题:

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

当您可以随时在SELECT语句中临时随意创建此列时,为什么还要这样做呢?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM