If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > DB2 > INSERT - integer not null PK

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 06-03-10, 06:10
goldfishhh goldfishhh is offline
Registered User
 
Join Date: Nov 2004
Posts: 54
INSERT - integer not null PK

I'm trying to do an insert of some new records and my source is a flat text file that is length delimited. It contains one record per row except for the primary key field, an integer which is not null and PK.

I'm trying to do something like this:

Code:
INSERT INTO my.desttable

SELECT
  (SELECT max(id) FROM my.desttable) +1           -- id,
, col1                                                            -- name,
, col2                                                            -- age

FROM
  my.source
What happens is max(id) always ends up being the same thing and I get a duplicate number error.

I've also tried to timestamp() and then pull out just the numbers, but that results in the same timestamp().

Where am I going wrong?

DB2 v9.1 on zOS
Reply With Quote
  #2 (permalink)  
Old 06-03-10, 08:02
dav1mo dav1mo is offline
Registered User
 
Join Date: Dec 2007
Location: Richmond, VA
Posts: 782
Its the same unit of work so the max number will be the same for all in that select. You should look at either sequences or identity column.
Dave
Reply With Quote
  #3 (permalink)  
Old 06-03-10, 10:38
tonkuma tonkuma is offline
Registered User
 
Join Date: Feb 2008
Location: Japan
Posts: 2,193
Quote:
I'm trying to do an insert of some new records and my source is a flat text file that is length delimited.
It contains one record per row except for the primary key field, an integer which is not null and PK.
I couldn't understand well the explanation.
One reason might be inappropriate words(e.g. record, flat text file) were used in the explanation.
Another reason might be my poor English capability.
(What is "It"? my.source? or my.desttable?)

So, I'll ignore that.

Looking into the Code, it would be changed like this:
Code:
INSERT INTO my.desttable
SELECT
       (SELECT max(id) FROM my.desttable)
       + rn
     , col1
     , col2
  FROM
       (SELECT
               col1
             , col2
             , ROW_NUMBER() OVER() AS rn
          FROM
               my.source
       ) q
;
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On