3

I am trying to come up with a DB2 SQL statement that does the following, but I am not sure if this is allowed.

I know that it's possible to insert into tableA ( ... ) Values (?,?,?,...)
and then assign values to those parameters ?.

Is it possible to pre-defined the value of one of the parameter?

For example, one of the column that I am trying to insert is the ID column and I would like to make it something like select max(id) + 1 from tableA.

This is what I am trying to get to - is this syntax possible in db2?

insert into tableA (ID, Text1, Text2) VALUES (select max(id)+1 from tableA, ?, ?)

Anyways - any help would be appreciated!

thanks!!

2
  • I am curious why you'd not want to use autogenerated primary keys? CREATE TABLE mytable (id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, ...) Commented Apr 18, 2012 at 13:55
  • I didn't have control on how the table was created, but thanks for the pointer ! Commented Apr 18, 2012 at 13:59

3 Answers 3

4

this should works :

 insert into tableA values((select max(id)+1 from tableA),'text1','text')
Sign up to request clarification or add additional context in comments.

Comments

0

It sounds like you are wanting a primary key as an index on your table.

db2 alter table tableA add primary key (id)

This will create a column in your table which will auto-increment when you add a new record. Source ( http://www.ibm.com/developerworks/data/library/techarticle/dm-0401melnyk/ )

2 Comments

Yes - this is one way to go about it to answer my question - but one the other hand is there a way to mix/match values and params?
In DB2, INSERT can take a VALUES argument OR a SELECT, but not both in one query: publib.boulder.ibm.com/infocenter/iseries/v5r4/…
0

You can also try using the OVERRIDING USER VALUE parameter:

INSERT INTO TableA
OVERRIDING USER VALUE 
SELECT 0,Text1, Text2
From TableB 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.