当前位置:Gxlcms > 数据库问题 > SQL Proc(存储过程)/tran(事物)

SQL Proc(存储过程)/tran(事物)

时间:2021-07-01 10:21:17 帮助过:3人阅读

存储过程好比C#方法

1.事物写在过程里面,直接调用存储过程

1.1没有参数的过程

/*transaction事物,procedure存储过程*/
create proc CopyTable_1_10000 
as
begin tran--开始事物 
declare @tran_error int;--声明参数
set @tran_error=0;--给参数赋值
declare @i int,@y int;
set @i=10000;set @y=1;
/*新表不存在时,将数据复制到新表
select * into table_3 from(select*from table_1)as a
*/
while @y<@i   --循环
begin
   /*新表存在,将数据复制*/
   insert into table_3(materialName,Mtype) select materialName,Mtype from table_1
   set @y=@y+1;--循环条件
   set @tran_error=@tran_error+@@ERROR;--事物用于记录错误的系统参数
end
/*判断事物执行是否出错*/
if(@tran_error>0)--@tran_error大于1代表出错,事物回滚
begin
 rollback tran;
 print ‘事物回滚‘
end
else
begin
 commit tran
 print ‘提交事物‘
end
--调用存储过程 exec CopyTable_1_10000

1.2带传参的过程

--PROC带参数
create proc showDescription
@Mtype int--需要传递的参数 
as
begin
select * into  #table_3 from
(select table_1.materialName,table_2.MtypeDescription from table_1 left join table_2 
 on table_1.Mtype=table_2.id
 where table_1.Mtype=@Mtype)as c
 select * from #table_3
end
--调用,传递@Mtype参数
exec showDescription @Mtype=2
--删除
drop proc showDescription

  

 

SQL Proc(存储过程)/tran(事物)

标签:

人气教程排行