zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    算法:最小公倍数的求解方法
    使用C语言中qsort()函数对浮点型数组无法成功排序的问题
    用两个栈模拟实现一个队列
    单链表反向查找
    单链表逆序
    斐波那契(Fibonacci)数列的几种计算机解法
    最大子列和问题
    Visual Studio个人常用快捷键
    数字根(digital root)
    秦九韶算法(霍纳算法)求解多项式
  • 原文地址:https://www.cnblogs.com/gdjlc/p/2086891.html
Copyright © 2011-2022 走看看