sql游标

Posted SmilePastaLi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql游标相关的知识,希望对你有一定的参考价值。

记录下游标的使用,也可以在游标中嵌入循环,即双重循环,代码如下

 

declare @GName  varchar(50),@GcName varchar(50)--临时变量,用来保存游标值
DECLARE My_Cursor CURSOR --定义游标
FOR (SELECT GoodsName,GcName FROM dbo.Tc_RegInStore GROUP BY GoodsName,GcName) --查出需要的集合放到游标中
OPEN My_Cursor; --打开游标
FETCH NEXT FROM My_Cursor INTO @GName,@GcName ; --读取第一行数据
WHILE @@FETCH_STATUS = 0
    BEGIN
    
SELECT @GName AS GoodName,@GcName AS BrandName, 
(select ISNULL(Sum(convert(bigint,RegEndCode)-convert(bigint,RegStartCode))+count(*),0) AS InNum FROM dbo.Tc_RegInStore  
WHERE GoodsName [email protected] AND [email protected]) AS InNum,
(SELECT  count(*) AS OutNum FROM TC_LogisticsCode t 
INNER JOIN dbo.Tc_RegOutStore b 
ON convert(bigint,t.FLgsBar) BETWEEN convert(bigint,b.RegStartCode) AND convert(bigint,b.RegEndCode)
WHERE  [email protected] AND [email protected]) AS OutNum

        FETCH NEXT FROM My_Cursor INTO @GName,@GcName; --读取下一行数据
    END
CLOSE My_Cursor; --关闭游标
DEALLOCATE My_Cursor; --释放游标

  

游标中嵌入循环,如下:

 

技术分享
 DECLARE @i INT;
 DECLARE @FAntiQryID INT;
 DECLARE @FFAntiFakeCode VARCHAR(50)
--临时变量,用来保存游标值
 DECLARE My_Cursor CURSOR --定义游标
 FOR
    ( SELECT    FFAntiFakeCode
      FROM      dbo.temp0706
      WHERE     FSystime > 2017-06-26
                AND FsearchNum = 0
      GROUP BY  FFAntiFakeCode
    )
 --查出需要的集合放到游标中
 OPEN My_Cursor;
 --打开游标
 FETCH NEXT FROM My_Cursor INTO @FFAntiFakeCode;
 --读取第一行数据
 WHILE @@FETCH_STATUS = 0 
    BEGIN
        IF NOT OBJECT_ID(Tempdb..#B) IS NULL 
            DROP TABLE #B
        CREATE TABLE #B ( [FAntiQryID] INT )
        INSERT  #B
                SELECT  FAntiQryID
                FROM    dbo.temp0706
                WHERE   FFAntiFakeCode = @FFAntiFakeCode
                ORDER BY FSystime DESC 
        --SELECT * FROM #B
        
        SET @i = 0;
        --循环码的记录数
        WHILE EXISTS ( SELECT   FAntiQryID
                       FROM     #B ) 
            BEGIN
                SET ROWCOUNT 1
                SET @i = @i + 1
                SELECT  @FAntiQryID = FAntiQryID
                FROM    #B
                UPDATE  dbo.temp0706
                SET     FsearchNum = @i
                WHERE   FAntiQryID = @FAntiQryID  --按时间递增更新查询次数
                SET ROWCOUNT 0
                DELETE  FROM #B
                WHERE   FAntiQryID = @FAntiQryID
            END
        DROP TABLE #B
        
        FETCH NEXT FROM My_Cursor INTO @FFAntiFakeCode; --读取下一行数据
    END
 CLOSE My_Cursor;
 --关闭游标
 DEALLOCATE My_Cursor; --释放游标
View Code

 

以上是关于sql游标的主要内容,如果未能解决你的问题,请参考以下文章

SQL记录-PLSQL包

如何优化使用游标的 PL/SQL 代码

游标的 PL/SQL 代码中的错误

过程中的PL/SQL游标问题

游标和递归sql 的一些代码

游标和递归sql 的一些代码