基础数据表:
select * from dbo.RecommendationChanelVersionRelation;
数据如下:
要求按照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数据如下:
这样每组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 [email protected] where [email protected]
FETCH NEXT FROM My_Cursor into @rownum,@id; --读取第一行数据
END
CLOSE My_Cursor; --关闭游标
DEALLOCATE My_Cursor; --释放游标
GO
搞定!!!
分组PARTITION BY及游标CURSOR的用法,布布扣,bubuko.com