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

  • 相关阅读:
    自我理解:const char*, char const* and char *const
    获取任意控件的ID或窗口句柄
    Webmax 2.0开启无限量下载
    dotLucene搜索加入中文分词
    SQL SERVER获得指定表的主键
    LogExplore应用(ms sql server事物分析、数据恢复工具)[转载]
    电脑病之一
    查找数据库中记录数大于N的表
    视图
    获取生日提醒数据
  • 原文地址:https://www.cnblogs.com/FH-cnblogs/p/3223125.html
Copyright © 2011-2022 走看看