SQL Server 存储过程之嵌套游标

来源:互联网 发布:maven 知乎 编辑:程序博客网 时间:2024/04/28 00:59
USE [NFGC_Workflow]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO-- =============================================-- Author:Ben.Jiang-- Create date:2011/9/13-- Description:添加库存警告-- =============================================ALTER PROCEDURE [dbo].[Insert_AlltblStockLimit] @Company NVARCHAR(50),@MaxEnable bit,@MinEnable bit,@Max NVARCHAR(50),@Min NVARCHAR(50),@MaxAlertAheadDays int,@MinAlertAheadDays intASBEGINDECLARE @CustomerCur CURSOR;--声明外层游标DECLARE @Id NVARCHAR(50),@ItemCode NVARCHAR(50),@customer NVARCHAR(50);--获取所有客户记录SET @CustomerCur=CURSOR FOR select distinct [cust-num] from(SELECT A.[cust-num],ISNULL(B.name,A.[name]) as name from dbo.Erp_custaddr a LEFT JOIN dbo.Erp_custaddr_CHS B ON A.[cust-num]=B.[cust-num] AND A.[cust-seq]=B.[cust-seq] where A.[credit-hold]='False' and A.[cust-seq]=0) as cust OPEN @CustomerCur --打开外层游标FETCH NEXT FROM @CustomerCur INTO @customer--提取外层游标行WHILE(@@FETCH_STATUS=0)BEGINDECLARE @varCur CURSOR;--声明内层游标--获取每一个客户的商品记录SET @varCur = CURSOR FOR SELECT DISTINCT item FROM dbo.Erp_itemcust AS A INNER JOIN [Erp_ux-customer]     AS B ON  A.[cust-num]=B.[cust-num]  AND B.[cust-num] IS NOT NULL   AND LEN(A.[cust-num])>0 AND B.[cust-seq]=0 INNER JOIN Erp_imsAs AS C ON C.sItem=A.item AND C.sCust=A.[cust-num]  AND C.cActFlg = '0' WHERE  A.item IS NOT NULL  AND LEN(A.item)>0 AND  A.[cust-num]=@customer; OPEN @varCur --打开内层游标FETCH NEXT FROM @varCur INTO @ItemCodeWHILE(@@FETCH_STATUS=0)BEGIN        IF (exists(SELECT Id from tblStockLimit where Company=@Company and Custnum=@customer and ItemCode=@ItemCode))            --存在该记录更新记录BEGINSET @Id=(SELECT Id from tblStockLimit where Company=@Company and Custnum=@customer and ItemCode=@ItemCode)update tblStockLimit set MaxEnable=@MaxEnable,Max=case when @Max<>'' then @Max else null end,MaxAlertAheadDays=case when @MaxAlertAheadDays<>'' then @MaxAlertAheadDays else null end,MinEnable=@MinEnable,Min=case when @Min<>'' then @Min else null end,MinAlertAheadDays=case when @MinAlertAheadDays<>'' then @MinAlertAheadDays else null end where Id=@Id;END                ELSE            --不存在该记录新增记录BEGINinsert into tblStockLimit(Company,Custnum,ItemCode,MaxEnable,Max,MaxAlertAheadDays,MinEnable,Min,MinAlertAheadDays)values('NFGS',@customer,@ItemCode,@MaxEnable,case when @Max<>'' then @Max else null end,case when @MaxAlertAheadDays<>'' then @MaxAlertAheadDays else null end,@MinEnable,case when @Min<>'' then @Min else null end,case when @MinAlertAheadDays<>'' then @MinAlertAheadDays else null end);ENDFETCH NEXT FROM @varCur INTO @ItemCode--内层游标向下移动一行 ENDCLOSE @varCurDEALLOCATE @varCurFETCH NEXT FROM @CustomerCur INTO @customer--内层游标结束后,外层游标继续向下移动一行 ENDCLOSE @CustomerCurDEALLOCATE @CustomerCurEND

原创粉丝点击