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]
遊標中嵌入循環,如下:
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 =View Code0 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遊標