zoukankan      html  css  js  c++  java
  • 调整主建为自增、表内自关联的主建顺序

    问题: 调整主建为自增、表内自关联的主建顺序

    解答:
    -- 想用外键的级联修改,但表内自关联的方式不支持级联修改、删除

    -- 还有另外一个办法,先将外键删除,再用触发器实现级联更新,然后再添加外键

    -- 第三种方式:对欲修改的表中加入一个自增列,将数据导入一个临时表
    select *, identity(int, 1, 1) as id into #t
    from A

    /*---上面的语句应该写成如下,因为 A表的OID为自增字段,不能再直接加上 identity(int, 1, 1) as id1
     select * into #tt1
     from A
     
     alter table #tt1 add id1 bigint
     
     update #tt1
     set id1 = OID
     
     alter table #tt1 drop column OID
     
     sp_rename '#tt1.id1', 'OID', 'column' -- 此处不能通过, 因为在当前数据库中是找不到 #tt1 表的,必须到 tempdb 下才能操作
     
     select *, identity(int, 1, 1) as id1 into #t -- 此处只能用  select id1, vName...., identity(int, 1, 1) as id2 into #t from #tt1
     from #tt1
     
     drop table #tt1
    ---*/

    select * from #t

    -- 然后设置外键关联的转变,从依赖于OID,转变为依赖自增的ID
    update #t
    set lParent = t.id2
    from
    (
     select t1.OID as id1, t1.lParent as lParent1, t2.id as id2
     from #t as t1 join #t as t2 on t1.lParent = t2.OID
    ) as t
    where t.id1 = #t.OID

    select OID, lParent, id
    from #t


    -- 删除表中所有行,并且将自动增值的列初始为种子值
    truncate table A

    -- 插入调整了顺序的数据
    insert into A(字段列表)

    from #t
    order by id

    select *
    from tFunctions

    -- 完成

  • 相关阅读:
    java面试题2
    java面试题
    查询数据库表字段名和字段类型等信息
    安装eclipse
    redis启动
    eclipse离线安装sonarlint插件
    大白菜安装win10系统
    制作window.ios镜像
    大白菜装机系统
    传递中文字符串时,转换编码格式
  • 原文地址:https://www.cnblogs.com/zhaoguan_wang/p/sqlserver.html
Copyright © 2011-2022 走看看