0

I want to write a update SQL statement, but one conidtion of this statement is the result from a select SQL statement, and I also want to return the result of the select SQL statement.

Like this: update ... set ... where id = (select id from ...)

I want to return the value of id back.

Does anybody know how should I do this?

Thanks in advance!

1
  • Probably you should create a procedure in your RDBMS and call that from java. Commented Oct 7, 2011 at 7:39

4 Answers 4

2

I don't believe that's possible in one statement. Update then query (select) the new value, or query the value first, and then submit an update.

Alternative would be a stored procedure on the database, which executes the multiple queries and returns the result for you.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I would follow stored procedure approach.
A word of warning with store procedures: Unless you're using them already, they will take you down a route which becomes database specific. If you want to remain DB agnostic, I'd tend to stay with multiple simple sql queries.
0

This is not possible in all Java database frameworks that I know. Probably you need to separate your query and update in Java.

Comments

0

I don't see any problem in using a subselect in a WHERE clause of an update statement.

For the second request, getting back the value of id, I know this is possible in DB2, and maybe others implement that syntax too:

SELECT id FROM FINAL TABLE (
  update ... set ... where id = (select id from ...)
)

This works also for INSERT and DELETE statements. (See the documentation.)

Comments

0

Update statements won't return the updated datasets. The select in that case would be a subselect that isn't directly accessible.

You'd thus have to use at least two queries:

  1. select the ids you want
  2. call the update query passing the previously selected ids as a parameter

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.