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

  • 相关阅读:
    windows下安装和设置Git客户端
    普通年金终值和现值计算(白话版)
    Git Http Server
    Python容器数据类型——collections
    模拟二进制实现减法
    自己写的线程池
    买书问题
    电梯调度算法
    Python文本常量和模板——string
    shell变量设置与显示
  • 原文地址:https://www.cnblogs.com/gdjlc/p/2086891.html
Copyright © 2011-2022 走看看