I am trying to write a sproc with a transaction. Can anybody tell me if there would be any issues with code below, or if it will work as intended?
ALTER procedure [dbo].[DeleteMetricMeter]
(
@SectionID int,
@MetricMeterID int,
@Result bit output
)
as
declare @MetricMeterCount int
declare @err int
declare @rowcount int
set xact_abort on
begin tran
select @MetricMeterCount = count(*) from luMetricMeters
where fkSectionID = @SectionID
select @err = @@error, @rowcount = @@rowcount
if (@err <> 0) or (@rowcount = 0)
begin
goto on_error
end
delete from luMetricMeterList
where pkMetricMeterID = @MetricMeterID
select @err = @@error, @rowcount = @@rowcount
if (@err <> 0) or (@rowcount = 0)
begin
goto on_error
end
delete from luMetricMeters
where pkMetricMeterID = @MetricMeterID
select @err = @@error, @rowcount = @@rowcount
if (@err <> 0) or (@rowcount = 0)
begin
goto on_error
end
if (@MetricMeterCount = 1)
begin
delete from luMetricSections
where pkSectionID = @SectionID
select @err = @@error, @rowcount = @@rowcount
if (@err <> 0) or (@rowcount = 0)
begin
goto on_error
end
end
commit tran
set @result = 1
return @result
on_error:
rollback tran
set @result = 0
return @result
There are a few issues with the procedure:
Your code is not thread safe. The MetricMeterCount query should be changed to this to prevent other threads from performing the delete in between your select & the execution of the delete:
I would write the code like this:
Note: The return values should be 0 for success and a negative number for failure.