分组PARTITION BY及游标CURSOR的用法

时间:2022-09-07 08:17:13

基础数据表:

select * from dbo.RecommendationChanelVersionRelation;

数据如下:

分组PARTITION BY及游标CURSOR的用法

要求按照ChannelVersionID分组,对每组中的OrderId根据ID由小到大的顺序,更新为1,2,3,4,5...

方法一(分组PARTITION BY):

IF OBJECT_ID('tempdb..#tempdt') IS NOT NULL
DROP TABLE #tempdt;
select RowNumOrderByChannelVersionID = ROW_NUMBER() OVER ( PARTITION BY ChannelVersionID ORDER BY orderid,id),* into #tempdt
from dbo.RecommendationChanelVersionRelation
order by orderid

#tempdt数据如下:

分组PARTITION BY及游标CURSOR的用法

这样每组ChannelVersionID都有了1,2,3....表示按照一定规则排序的行号RowNumOrderByChannelVersionID:

最后一步,更新:

update rcr set rcr.OrderId=t.RowNumOrderByChannelVersionID
from #tempdt t left join dbo.RecommendationChanelVersionRelation rcr on t.id=rcr.id

 

方法二(游标CURSOR):

declare @rownum int;
declare @id int;
DECLARE My_Cursor CURSOR --定义游标
FOR (select ROW_NUMBER() over(PARTITION BY ChannelVersionID ORDER BY orderid,id) as num,id from dbo.RecommendationChanelVersionRelation ) --查出需要的集合放到游标中
for update of orderid
OPEN My_Cursor; --打开游标
FETCH NEXT FROM My_Cursor into @rownum,@id; --读取第一行数据
while @@FETCH_STATUS = 0
BEGIN
UPDATE dbo.RecommendationChanelVersionRelation set orderid=@rownum where id=@id
FETCH NEXT FROM My_Cursor into @rownum,@id; --读取第一行数据
END
CLOSE My_Cursor; --关闭游标
DEALLOCATE My_Cursor; --释放游标
GO

 

搞定!!!