I have created the following query which is now in one of my java classes being used by Hibernate.
private static final String COUNT_INTERQUARTILE_SQL
= " SET @number_of_rows \\:= (SELECT COUNT(*) FROM carecube.visit)" +
" SET @quartile \\:= (ROUND(@number_of_rows*0.25))" +
" SET @medianquartile \\:= (ROUND(@number_of_rows*0.50))" +
" SET @sql_q1 \\:= (CONCAT('(SELECT 'Q1' AS quartile, visit.id FROM carecube.visit order by visit.id LIMIT 1 OFFSET ', @quartile, ')'))" +
" SET @sql \\:= (CONCAT_WS(' UNION ', @sql_q1, @sql_med))" +
" PREPARE stmt1 from @sql;" +
" EXECUTE stmt1;";`
The stack trace complains of a syntax errors for each line where I've set a mysql variable. Obviously it works in MySQL just fine.
I read that I can use double backslashes with assignments in Hibernate. This is the first time I've tried to use MySQL variables with Hibernate so am unsure if I'm missing anything out and whether 'PREPARE' and 'EXECUTE' are necessary?
Can someone with more knowledge point me where I am going wrong?
Also, where I am selecting Q1, I've placed that in single quotes, in MySQL workbench it is double quotes.
EDIT: I've added double quotes so hibernate doesn't throw a sissy fit with the assignments. I still can't for the life of me, figure out why I cannot just use '@sql' after i've prepared it.
EDIT: I receive the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'PREPARE stmt1 from @sql_max; EXECUTE stmt1' at line 1
Thanks