patternsqlMinor
Multiple SQL statements in a single transaction
Viewed 0 times
sqlstatementssingletransactionmultiple
Problem
Using the following query I'm doing transactions with two tables
First SalaryTrans table is updated. Then all matching records in CarriedForward table are deleted and new details are entered.
I just want to know whether this approach is acceptable or there are better ways to write this.
BEGIN TRANSACTION
UPDATE SalaryTrans SET carried_forward_amount = @carriedForwardAmount, net_wage=@netWage, processed_date = @processedDate WHERE employee_id=@employeeID AND reference = @reference
DELETE FROM CarriedForward WHERE employee_id = @employeeID
INSERT INTO CarriedForward (employee_id, carried_forward_amount) VALUES(@employeeID, @carriedForwardAmount)
COMMIT;First SalaryTrans table is updated. Then all matching records in CarriedForward table are deleted and new details are entered.
I just want to know whether this approach is acceptable or there are better ways to write this.
Solution
In terms of the raw/basic functionality, what you have is fine. The transactional logic is good.
Readability is the only concern I have, and would rewrite your code as (note, there are some spaces I added around some
I assume the business logic is correct. It is unusual to have a table in a database where deletes happen. I am more accustomed to having some sort of history for the data, and the delete is a logical thing, not a real delete. This is normally for audit/reporting purposes.
Readability is the only concern I have, and would rewrite your code as (note, there are some spaces I added around some
= conditions):BEGIN TRANSACTION
UPDATE SalaryTrans
SET carried_forward_amount = @carriedForwardAmount,
net_wage = @netWage,
processed_date = @processedDate
WHERE employee_id = @employeeID
AND reference = @reference
DELETE FROM CarriedForward
WHERE employee_id = @employeeID
INSERT INTO CarriedForward (employee_id, carried_forward_amount)
VALUES(@employeeID, @carriedForwardAmount)
COMMIT;I assume the business logic is correct. It is unusual to have a table in a database where deletes happen. I am more accustomed to having some sort of history for the data, and the delete is a logical thing, not a real delete. This is normally for audit/reporting purposes.
Code Snippets
BEGIN TRANSACTION
UPDATE SalaryTrans
SET carried_forward_amount = @carriedForwardAmount,
net_wage = @netWage,
processed_date = @processedDate
WHERE employee_id = @employeeID
AND reference = @reference
DELETE FROM CarriedForward
WHERE employee_id = @employeeID
INSERT INTO CarriedForward (employee_id, carried_forward_amount)
VALUES(@employeeID, @carriedForwardAmount)
COMMIT;Context
StackExchange Code Review Q#58272, answer score: 8
Revisions (0)
No revisions yet.