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


Thanks
snigerAsked:
Who is Participating?
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 OlsenData Warehouse Architect / DBACommented:
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
  (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!
Kent
0

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 ?
0
Kent OlsenData Warehouse Architect / DBACommented:
The DB2 "LOCK TABLE" statement.  :)


Your stored procedure will execute these 3 statements:

LOCK TABLE mytable;

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

COMMIT;

Open in new window


Then just wrap that with the Store Procedure construct and you're done.
0
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
DB2

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.