zoukankan      html  css  js  c++  java
  • (SQL游标) 整合省市

    declare @ParentID int
    declare @num int
    set @num =0
    --声明一个游标mycursor,select语句中参数的个数必须要和从游标取出的变量名相同
    declare mycursor cursor for
    select ProID as ParentID from Bms_Province p

    --打开游标
    open mycursor

    --从游标里取出数据赋值到我们刚才声明的2个变量中
    fetch next from mycursor into @ParentID

    --判断游标的状态
    --0 fetch语句成功
    ---1 fetch语句失败或此行不在结果集中
    ---2被提取的行不存在
    while (@@fetch_status=0)
    begin

    --显示出我们每次用游标取出的值
    print '游标成功取出一条数据'

    set @num =@num+1
    print @num
    insert into Bms_Areas
    select
    (case when T.CityID=0 then 0 else -99 end ) as ParentID,
    (case when T.CityID=0 then '0'+CONVERT(VARCHAR(10),T.ProID)
    else '00'+CONVERT(VARCHAR(10),T.CityID) end) as AreaCode,
    T.ProName as AreaName,'' as Notes,
    (case when T.CityID=0 then 1 else 2 end) as LevelNum,
    0 as IsDefault,1 as IsValid,0 as IsDel
    from (
    select p.ProID,p.ProName,p.ProSort,0 as CityID,p.ProRemark from Bms_Province p where ProID=@ParentID
    union select c.ProID,c.CityName,c.CitySort,c.CityID,'' as ProRemark from Bms_City c where ProID=@ParentID
    ) T order by CityID

    UPDATE T SET ParentID =
    (select top 1 AreaID from Bms_Areas where ParentID=0 order by AreaID desc)
    from (select * from Bms_Areas where ParentID=-99 and AreaID>
    (select top 1 AreaID from Bms_Areas where ParentID=0 order by AreaID desc)) T


    --用游标去取下一条记录
    fetch next from mycursor into @ParentID
    end
    --关闭游标
    close mycursor
    --撤销游标
    deallocate mycursor

  • 相关阅读:
    Code Forces Gym 100886J Sockets(二分)
    CSU 1092 Barricade
    CodeChef Mahesh and his lost array
    CodeChef Gcd Queries
    CodeChef GCD2
    CodeChef Sereja and LCM(矩阵快速幂)
    CodeChef Sereja and GCD
    CodeChef Little Elephant and Balance
    CodeChef Count Substrings
    hdu 4001 To Miss Our Children Time( sort + DP )
  • 原文地址:https://www.cnblogs.com/FH-cnblogs/p/3223125.html
Copyright © 2011-2022 走看看