I have an MSSQL (very much simplified) query that looks like this:
BEGIN TRY
BEGIN TRANSACTION
IF OBJECT_ID(N\'tempdb..#temptable\') IS NOT NULL DROP TABLE #temptable;
CREATE TABLE #temptable (
id INT,
id2 INT
);
INSERT INTO #temptable (
id
id2
)
VALUES
%1$s; -- One or more (int, int) pairs
INSERT INTO anothertable (
--other stuff
) VALUES (
-- values dervied from #temptable
);
INSERT INTO anothertable2 (
--other stuff
) VALUES (
-- values dervied from #temptable
);
COMMIT TRANSACTION;
SELECT 1 AS Result;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
SELECT 0 AS Result, ERROR_MESSAGE() AS Error;
END CATCH
In the transaction, I need to be able to do a variable number of inserts, and also return the result of the transaction.
The %1$s
in the query string preferably something that I can feed into a NamedParameterJdbcTemplate
, which I call in the manner of:
// parameters is a Map<String, Object>
jdbcTemplate.queryForList(query, parameters)
- Due to the transactional and multi-statement nature of the query, I cannot use
batchupdate
to generate the parameterized inserts. - Due to the specific returns that I need from the query in the case of a failure, I cannot replace the
BEGIN TRANSACTION
with a java-side@Transactional
either. - Due to the variable nature of the number of inserts I need to make in
%1$s
, I cannot prepare the statement with?
s.
How can I best generate the values for %1$s
in the query?