sql server 创建存储过程,游标,事务

CREATE PROCEDURE [dbo].[M_CreateInventoryCk]
AS 
    DECLARE @tran_error INT;--记录错误数量
    
    DECLARE @cursor CURSOR  --游标
    
    BEGIN

        SET @cursor=cursor for select LogistHead.[Guid],OrderHead.Guid,LogistHead.Weight,LogistHead.Pack_No From dbo.Kj_Logistics_Head LogistHead
   INNER JOIN dbo.Kj_Order_Head OrderHead ON OrderHead.Guid=LogistHead.OrderPK AND OrderHead.Doc_Status='A023' 
    
        OPEN @cursor
        FETCH NEXT FROM @cursor INTO @M_ID, @OrderGuid, @CURSORWeight,
            @CURSORPack_No
        WHILE @@FETCH_STATUS = 0 
            BEGIN
            
                
                BEGIN TRY 
                    BEGIN TRAN
                    SET @tran_error = 0;
        
                    
                    INSERT  INTO [dbo].[Kj_Ni_Inventory_Head]
                            ( [Guid] ,
                              ShiperName
                            )
                            SELECT  GETDATE()--汇总时间
                                    ,
                                    ( CASE OrderHead.Biz_Type
                                        WHEN '1' THEN 'B2CJJ'
                                        WHEN '3' THEN 'BSJ'
                                        ELSE ''
                                      END ) ,
                                    CASE WHEN logistHead.Customs_Code IN (
                                              '2314', '2381' ) THEN '320220'
                                         WHEN logistHead.Customs_Code IN (
                                              '2308' ) THEN '320150'
                                         ELSE '海关编码不是苏州和南京'
                                    END ,
                                    ( SELECT    REPLACE(LTRIM(NEWID()), '-',
                                                        '')
                                    )
                            FROM    dbo.Kj_Logistics_Head logistHead
                                    INNER JOIN dbo.Kj_Order_Head OrderHead ON logistHead.OrderPK = OrderHead.Guid
                            
   
                 
                END TRY

                BEGIN CATCH
                    PRINT '出现异常,错误编号:' + CONVERT(VARCHAR, ERROR_NUMBER())
                        + ',错误消息:' + ERROR_MESSAGE()
                    SET @tran_error = @tran_error + 1
                END CATCH

                IF ( @tran_error > 0 ) 
                    BEGIN
                    --执行出错,回滚事务
                        ROLLBACK TRAN;
        
                    END
                ELSE 
                    BEGIN
                    --没有异常,提交事务
                        COMMIT TRAN;
                        
                    END
                FETCH NEXT FROM @cursor INTO @M_ID, @OrderGuid, @CURSORWeight,
                    @CURSORPack_No
            END

  
        CLOSE @cursor
        DEALLOCATE @cursor
    END

 

posted @ 2020-05-21 15:16  Vaynedy  阅读(254)  评论(0编辑  收藏  举报