首页 > 代码库 > sql游标
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 =@GName AND GcName=@GcName) 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 t.FGoodsName=@GName AND t.BrandName=@GcName) AS OutNum FETCH NEXT FROM My_Cursor INTO @GName,@GcName; --读取下一行数据 ENDCLOSE 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; --释放游标
sql游标
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。