tags:

views:

109

answers:

3

Hi,

I'd like to execute something like this on my MySQL server:

SET @id=(SELECT id FROM lookupTable WHERE field=?);
(SELECT * FROM table2 WHERE id=@id)
UNION
(SELECT * FROM table3 WHERE id=@id)
UNION
(SELECT * FROM table4 WHERE id=@id);

This works fine from the console, but not from my Java PreparedStatement. It throws an exception with a syntax error at the ';' separating the statements. I like the variable because I don't have to repeat the lookup clause, but I could rewrite it if necessary. The equivalent JOIN is a little awkward with the UNION clauses too.

Thanks,

Joshua

+1  A: 

Just running this as two separate queries (within one connection) should give you same results.

Mchl
I was hoping to avoid the network time twice, but it seems unavoidable here. Maybe this is a security feature to avoid SQL injection.
Joshua Martell
@Joshua, you can batch queries to the server and avoid the multiple network trips.
ddimitrov
A: 

Yes, you can execute multiple statements. You just need to remove the ;s that are causing the syntax error. I set up a similar example on SQL Server and had to declare the scalar like so:

DECLARE @id int 
SET @id=(SELECT id FROM ...

I'm not sure if that's required in MySQL or not, but Java give me a very specific error message that led me right to the problem.

Bill the Lizard
This doesn't work for me in MySQL.
Joshua Martell
@Joshua: What error are you getting now? Did you remove both `;` characters? You do need to remove the one at the end also. Can you post your code?
Bill the Lizard
+1  A: 

JDBC has never supported parsing delimited queries. Each invocation is one trip to the database. Perhaps you can achieve what you meant to doing PreparedStatement.addBatch() for each separate query, then executing and retrieving the two resultsets ?

ddimitrov