db2 - u

I want to create a new record , the id is not defined as autoincrement. How to write a stored procedure, which would do this

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kent OlsenDBACommented:
Hi sniger,

You'll have to create the ID value yourself.  This is not best practice, and should be avoided if there are a lot of inserts to be done, but it's pretty easy.

INSERT INTO mytable (id, p1, p2, ..., pn)
  (SELECT max (ID) FROM mytable) + 1, v1, v2, ..., vn)
FROM another_source;

I suggest that you lock the table immediately before you execute that and do an immediate commit afterwards to prevent duplicates if the application(s) try to insert two rows simultaneously.

Good Luck!

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
snigerAuthor Commented:
thanks, how to lock the table ?
Kent OlsenDBACommented:
The DB2 "LOCK TABLE" statement.  :)

Your stored procedure will execute these 3 statements:

LOCK TABLE mytable;

INSERT INTO mytable (id, p1, p2, ..., pn)
  (SELECT max (ID) FROM mytable) + 1, v1, v2, ..., vn)
FROM another_source;


Open in new window

Then just wrap that with the Store Procedure construct and you're done.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.