• SQL标识列重新排序


    select *  from test

    id          title
    ----------- ------------------------------------
    1           20D32B5D-082C-47F1-9B84-FDD6F28700DC
    3           7662E2C4-5F3D-4425-91D1-DBAEEC70C02B
    5           F84E1617-D719-49DA-91F8-55DC76B66D2F
    6           53B15573-FD6D-46E5-A32C-BE8041E475D4
    8           7D42962D-365F-419A-B026-4A62440A3B43
    9           1A44340F-B78C-446E-A4D6-661EBA663EF3

    (6 行受影响)





    --先取消标识列id,再执行下面代码,执行后再设置id为标识列
    --下面代码中关键地方:
    --1、先找出总记录数作为循环次数
    --2、每次循环中要找出当前id
    declare @index int
    set @index = 1
    declare @count int
    set @count = (select count(*) from test)
    while(@index < @count+1)
    begin
        exec('update test set id=' + @index + ' where id = (select max(id) from (select top '+ @index + ' id from test) t)')
        set @index = @index + 1
    end




    select *  from test

    id          title
    ----------- ------------------------------------
    1           20D32B5D-082C-47F1-9B84-FDD6F28700DC
    2           7662E2C4-5F3D-4425-91D1-DBAEEC70C02B
    3           F84E1617-D719-49DA-91F8-55DC76B66D2F
    4           53B15573-FD6D-46E5-A32C-BE8041E475D4
    5           7D42962D-365F-419A-B026-4A62440A3B43
    6           1A44340F-B78C-446E-A4D6-661EBA663EF3

    (6 行受影响)

    =====================================================

    ------------------在网上看到的更好的方法:

    declare @i int
    set @i=0
    update test set id=@i,@i=@i+1

  • 相关阅读:
    最大上升子序列
    vue的keep-alive组件
    对小程序的研究3
    对getBoundingClientRect属性的研究
    消除浮动的方式
    对微信小程序的研究2
    对小程序的研究1
    对props的研究
    对provide/inject的研究
    对calc()的研究
  • 原文地址:https://www.cnblogs.com/gdjlc/p/2086891.html
Copyright © 2020-2023  润新知