存储过程好比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
1.3带输出参数
if exists (select * from sys.procedures where name ='proc_getCourseInfo')
drop proc proc_getCourseInfo
go
create proc proc_getCourseInfo
@gradeid int,
@outparameter int output--输出参数
as
begin
select g.g_banji,c.c_CourseName,c.c_teacher,c.c_date,c.c_time from Course c left join grade g on c.c_gradeid=g.g_id where g.g_id=@gradeid;
select @outparameter=COUNT(*) from Course;
end declare @p int
exec proc_getCourseInfo @gradeid=2,@outparameter=@p output
select @p