国家统计局县及县以上行政区划导入SQL Server步骤

一、需求

将国家统计局发布的县及县以上行政区划代码导入SQL Server数据库,最终表格式:

create table City
(
    Id int identity(1,1) primary key,
    Name nvarchar(20),
    ParentId int
)

二、导入步骤

1.复制最新县及县以上行政区划代码(截止2011年10月31日)粘贴到记事本;
2.去掉北京、重庆、天津、上海四个直辖市的市辖区和县,底下行政区提一级(去掉两个空格);
3.去掉河南省、湖北省、海南省、新疆维吾尔自治区四个省直辖县级行政区划,底下行政区提一级(去掉两个空格);
4.替换" "(去掉两个空格)为,,保存为city.csv,在Excel中打开后再另存为city.xls;
5.打开SQL Server Management Studio,将city.xls数据导入到c1表,字段为f1,f2,f3,f4;
6.运行以下sql语句完成转换:

--导入到c2
create table c2
(
    id int identity(1,1) primary key,
    f1 int,
    f2 nvarchar(20),
    f3 nvarchar(20),
    f4 nvarchar(20),
    parentid int
)
insert into c2(f1,f2,f3,f4,parentid)
select f1,f2,f3,f4,0 from c1 order by f1
--数据整理
update c2 set parentid=(select max(id) from c2 t2 where t2.id<c2.id and not t2.f3 is null) where not f4 is null
update c2 set parentid=(select max(id) from c2 t2 where t2.id<c2.id and not t2.f2 is null) where not f3 is null
update c2 set parentid=0 where not f2 is null
--最终数据
create table City
(
    Id int identity(1,1) primary key,
    Name nvarchar(20),
    ParentId int
)
insert into City(Name,ParentId)
select isnull(f2,'')+isnull(f3,'')+isnull(f4,''),parentid from c2
--验证
select * from c2 where parentid is null
select * from City left join c2 on City.Id=c2.id where City.ParentId<>c2.parentid


评论: 0 | 引用: 0 | 查看次数: 3942
发表评论
登录后再发表评论!