sql server存储过程的条件判断和事务管理

来源:互联网 发布:mac 问号重启选择网络 编辑:程序博客网 时间:2024/04/28 05:54

       通过sql server存储过程周期性地根据条件字段值设置其他字段,包括条件判断和事务管理。实例语句如下。

      数据库表(vipPoint)定义语句如下:

CREATE TABLE [dbo].[vipPoint] (
    
[userCode] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
    
[point] [int] NOT NULL ,
    
[currentStatus] [int] NOT NULL ,
    
[baseStatus] [int] NOT NULL 
ON [PRIMARY]
GO

      存储过程语句如下:

CREATE procedure vipProcess 
as
begin

    
if (MONTH(getdate())=7)
    
begin
        
begin transaction
        
update vipPoint set currentStatus=1 where baseStatus=1 and point>1000
        
update vipPoint set currentStatus=0 where baseStatus=1 and point<1000
        
update vipPoint set currentStatus=1 where baseStatus=0 and point>1500
        
update vipPoint set currentStatus=0 where baseStatus=0 and point<1500
        
/**update vipPoint set point=0**/
        
update vipPoint set point=10000000000000000000000000000
        
if (@@error<>0)
        
begin
            
print('rollback transaction')
            
rollback transaction
            
return 0;
        
end;
        
commit transaction
    
end;
end;
GO

        也可以如下:

CREATE procedure vipProcess 
as
begin

    
if (MONTH(getdate())=7)
    
begin
        
begin transaction
        
update vipPoint set currentStatus=case when point>=1000 then 1 when point<1000 then 0 end where baseStatus=1
        
update vipPoint set currentStatus=case when point>=1500 then 1 when point<1500 then 0 end where baseStatus=0
        
/**update vipPoint set point=0**/
        
update vipPoint set point=10000000000000000000000000000
        
if (@@error<>0)
        
begin
            
print('rollback transaction')
            
rollback transaction
            
return 0;
        
end;
        
commit transaction
    
end;
end;
GO