开发者

Is it possible in Java to retrieve tables of unrelated data in a single SQL query and resultset?

开发者 https://www.devze.com 2023-03-30 07:59 出处:网络
We have multiple tables that contain \"static\" key/value pairs, which are currently pulled using multiple SQL (MSSQL) queries. Is it possible to pull all of this data in one SQL query, so that we can

We have multiple tables that contain "static" key/value pairs, which are currently pulled using multiple SQL (MSSQL) queries. Is it possible to pull all of this data in one SQL query, so that we can reference each column key and column value in a single result set? So for example:

TABLE_ONE
id, my_key_name, my_value_name

TABLE_TWO
id, my_other_key_name, my_other_value_name

Keep in mind that开发者_开发知识库 the column names for the key and for the value are different for each table. Basically, we're trying to consolidate multiple calls into one. Is this a situation where we'll have to have multiple Java ResultSets and we'll just need to do the combining in the code?


How about

SELECT id, my_key_name, my_value_name
FROM   TABLE_ONE
UNION
SELECT id, my_other_key_name, my_other_value_name
FROM   TABLE_TWO

?

See: UNION


I don't know if you can do it in one Statement (by separating the queries with semicolons), but you can certainly create a stored procedure that returns multiple result sets.

After calling getResultSet, you can use the getMoreResults method (from java.sql.Statement) to move to the next ResultSet. It closes the current ResultSet, so you'll need to get whatever data you need to out of the first ResultSet before calling getMoreResults and getting the next ResultSet from the Statement.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号