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-EncryptDecrypt:DES
    Code-Helper:EncryptHelper.cs
    Code-Helper:EmailHelper.cs
    养生-影视:《长寿之道——长寿村里的百岁夫妻》
    影视-栏目:《致富经》
    影视-栏目:《远方的家》
    影视-纪录片:《长江行》
    影视-纪录片:《塔里木河》
    影视-纪录片:《天山脚下》
    Counting Lines, Words, and Characters with wc
  • 原文地址:https://www.cnblogs.com/FH-cnblogs/p/3223125.html
Copyright © 2011-2022 走看看