问题
I use the following statement to generate my primary key. table2 keeps the curent primary key. But it is too slow. How can i optimize this proces.
update table1 t set ID =ROW_NUMBER() OVER ();
update table1 t
set ID = (Select NUMGEN.currentvalue + ID from table1 data, table2 NUMGEN
where NUMGEN.tablename = 'table1' and t.Id = data.ID );
回答1:
Why are you doing primary keys this way. Why would you need to dynamically generate/modify your own id values?
If you need a unique generated id for a table, create a sequence and use that sequence value in your table. For example:
CREATE SEQUENCE <schema>.SEQ_SAMPLE_TABLE DATA TYPE BIGINT INCREMENT BY 1 NO ORDER NO CYCLE MINVALUE 100 MAXVALUE 9223372036854775807 CACHE 20;
to get a unique sequence to use as your primary key.
Then create a table with an ID as the primary key:
CREATE TABLE <schema>.SAMPLE_TABLE (
STATUS_ID BIGINT DEFAULT NULL ,
STATUS_DESC VARCHAR(80) DEFAULT NULL ,
CONSTRAINT <schema>.XPK_STATUS PRIMARY KEY( STATUS_ID ) );
and then to insert a row, you do:
insert into SAMPLE_TABLE (nextval for SEQ_SAMPLE_TABLE, 'This is working');
Most of this can come from the db2 manuals.
For example: Create Table: http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/admin/r0000927.htm
Create Sequence: http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/admin/r0004201.htm
EDIT: I should add -- the above is how we're doing it at my current client. Another way (perhaps better) is:
CREATE TABLE WIDGET_INVENT
( ROW_ID INT NOT NULL GENERATED ALWAYS AS IDENTITY
(START WITH 1, INCREMENT BY 1, NO CACHE),
WIDGET_NO CHAR(6),
INV_COUNT INT WITH DEFAULT 0
);
where you don't specify the sequences externally, but just build them into the table definition. In this case, when doing inserts, just don't reference the row_id column at all. For example, see here: http://www.ibm.com/developerworks/data/library/techarticle/0205pilaka/0205pilaka2.html
The first way, where you specify your own sequences, was partially done that way because of how they migrate some tables from one environment to the next. Sequences get mapped out from different sources with different start values, allowing easy merging of data. YMMV
来源:https://stackoverflow.com/questions/9703554/how-to-generate-the-primary-key-in-db2-sql-optimization