遊標在有時候會頗有用,在更新一部分很少的數據時,能夠很方便的更新數據,不須要再寫一個小工具來作了,直接寫 SQL 就能夠了html
下面來看一個實際示例:sql
-- 聲明字段變量 DECLARE @RegionCode INT; DECLARE @RegionName NVARCHAR(64); DECLARE @ProvinceId INT; -- 聲明遊標 DECLARE ProvinceCursor CURSOR FOR( SELECT Id AS ProvinceId, region.RegionCode,region.RegionName FROM dbo.Provinces AS province JOIN dbo.Regions AS region ON province.Name=SUBSTRING(region.RegionName,1, LEN(province.Name)) AND region.RegionType=1 ); -- 打開遊標 OPEN ProvinceCursor; -- 移動遊標,加載數據 FETCH NEXT FROM ProvinceCursor INTO @ProvinceId,@RegionCode,@RegionName; WHILE @@FETCH_STATUS = 0 BEGIN -- 根據遊標數據進行操做,這裏只輸出要執行的 SQL 腳本,也能夠直接 UPDATE,看本身須要 PRINT 'UPDATE dbo.Provinces SET Code = ' + CONVERT(NVARCHAR(12), @RegionCode)+', Name = N'''+@RegionName +''' WHERE Id = ' + CONVERT(NVARCHAR(12), @provinceId) +';'; -- 移動遊標到下一條數據 FETCH NEXT FROM ProvinceCursor INTO @ProvinceId,@RegionCode,@RegionName; END; CLOSE ProvinceCursor; DEALLOCATE ProvinceCursor;
DECLARE @projectId nvarchar(36) -- 聲明變量 DECLARE My_Cursor CURSOR --定義遊標 FOR (SELECT OriginalProjectId FROM dbo.CommunityProjects WHERE CommunityId = -1) --查出須要的集合放到遊標中 OPEN My_Cursor; --打開遊標 FETCH NEXT FROM My_Cursor INTO @projectId; WHILE @@FETCH_STATUS = 0 BEGIN UPDATE dbo.CommunityProjects SET CommunityId = CAST(ISNULL(( SELECT ZhongyiCommunityId FROM dbo.CommunityMappings WHERE FangdiCommunityId = @projectId ),'-1') AS INT) WHERE OriginalProjectId = @projectId FETCH NEXT FROM My_Cursor INTO @projectId; END CLOSE My_Cursor; --關閉遊標 DEALLOCATE My_Cursor; --釋放遊標
and moreapp
DECLARE @RegionCode INT; DECLARE @RegionName NVARCHAR(64); DECLARE @provinceId INT; DECLARE ProvinceCursor CURSOR FOR( SELECT RegionCode, RegionName FROM dbo.Regions WHERE RegionType = 1); OPEN ProvinceCursor; FETCH NEXT FROM ProvinceCursor INTO @RegionCode, @RegionName; WHILE @@FETCH_STATUS = 0 BEGIN SET @provinceId =ISNULL((SELECT Id FROM dbo.Provinces WHERE Name = @RegionName), 0); IF @provinceId > 0 PRINT 'UPDATE dbo.Provinces SET Code = ' + CONVERT(NVARCHAR(12), @RegionCode)+' WHERE Id = ' + CONVERT(NVARCHAR(12), @provinceId) +';'; ELSE PRINT 'INSERT INTO dbo.Provinces(Name,Code) VALUES(N''' + @RegionName + ''',' + CONVERT(NVARCHAR(12), @RegionCode)+ ');'; FETCH NEXT FROM ProvinceCursor INTO @RegionCode, @RegionName; END; CLOSE ProvinceCursor; DEALLOCATE ProvinceCursor;
在作一些小數據量的數據操做時,遊標會很是方便,並且遊標比較靈活,你能夠只生成更新數據的SQL,也能夠打印出數據更新先後的值,以便錯誤更新數據以後的數據恢復工具