sql存储过程编程带事务

时间:2023-03-09 01:22:27
sql存储过程编程带事务

CREATE PROCEDURE [dbo].[存储过程名字]
@错误参数_ErrorCode int output,
@参数1 int,
@参数2 varchar(20),
@参数3 varchar(20)
AS
--创建事务进行数据处理
begin tran Tran_XX
DECLARE @tran_error int;
SET @tran_error=0;
--查询数据库是否有要创建的临时表,如果有则删除
if OBJECT_ID('Test.dbo.#temptale1') is not null
begin
drop table #temptale1
end
if OBJECT_ID('Test.dbo.#temptale2') is not null
begin
drop table #temptale2
end
--尝试执行主体命令部分
begin try
update Company set  字段名称=@参数3 where id=@参数1
SET @tran_error = @tran_error + @@ERROR
select * into #temptable1 from 表1 where  字段名称=@参数3 and [State]=1;--临时表1
select * into #temptable2 from 表2 where 字段名称=@参数3;                       --临时表2
--修改临时表中的要修改的字段
update #temptable1 set 字段名称=@参数2
SET @tran_error = @tran_error + @@ERROR
update #temptable2 字段名称=@参数2
SET @tran_error = @tran_error + @@ERROR
--将临时表里的数据 插入到对应的表里
insert into 表1 select 字段1,字段2,,字段3,字段4 from #temptable1
SET @tran_error = @tran_error + @@ERROR
--测试部分(检查事务是否管用)
--SET @tran_error = @tran_error + 1
insert into 表2 select 字段1,字段2,,字段3,字段4,字段5,字段6,字段7 from #temptable2
SET @tran_error = @tran_error + @@ERROR
end try

begin catch
--出现错误@tran_error+1
SET @tran_error = @tran_error +1
end catch

if(@tran_error>0)
begin
--出现错误 回滚
rollback tran
--print '测试错误1'
end
else
begin
--正常执行
commit tran
end

--删除临时表
if OBJECT_ID('Test.dbo.#temptale1') is not null
begin
drop table #temptale1
end
if OBJECT_ID('Test.dbo.#temptale2') is not null
begin
drop table #temptale2
end
--返回回执
set @错误参数_ErrorCode=@tran_error