sunkezai 发表于 2018-10-16 12:25:28

一个Excel导入SQL Server的例子

  这个是Excel的,比如是test.xls
  

  欠费年份 欠费开始月份 欠费结束月份 应缴金额(月租)
  2001            9                  12                  94.4
  2008            5                  12                  88.8
  2010            8                     12               90.4
  ___________________________________________
  

  
这个是表:比如是a表
  a(pk,int,not null) //主键,自动增长
  b(varchar(19),null) //费款所属期
  c(decimal(10,2),null) //应缴金额
  ___________________________________________
  

  
现在我要将test.xls中的数据导入到a表,从开始月份到结束月份要做循环导入,比如第一条2001年的从9月到12月要录入4条数据到a表,导入后的格式如:
  select * from a
  

  
a      b       c
  1 2001-09 94.4
  2 2001-10 94.4
  3 2001-11 94.4
  4 2001-12 94.4
  

  
数据库是:MS Sql server 2008
  解析:
  思路一:可以使用OpenRowset查询导入到表变量中,再用游标循环赋值。方法如下:
  

use testdb2go/*******************建立测试数据***3w@live.cn***********************/IF NOT OBJECT_ID('') IS NULLDROP TABLE GOCREATE TABLE ( int> NVARCHAR(20) null, decimal(10,2) null)go/*******************启用Ad Hoc Distributed Queries***3w@live.cn***********************/--------USE master  --
------go--------sp_configure 'show advanced options', 1  --
------GO  --
----------reconfigure  --
--------启用分布式查询 Ad Hoc Distributed Queries  --
------sp_configure 'Ad Hoc Distributed Queries', 1  --
------GO  --
------reconfigure  --
------gouse testdb2go/*******************定义表变量***3w@live.cn***********************/Declare @TableVar table  (PKId
int primary key>,RYearint not null,BMonth int not null  ,EMonth
int not null,RMoney Decimal(15,2) not null----,d1 date null,d2 Date null)insert into @TableVar  (RYear ,BMonth ,EMonth ,RMoney)
select * from OpenRowSet('Microsoft.Jet.OLEDB.4.0','Excel 8.0;HDR=Yes;IMEX=1;Database=D:\test\test20110501.xls','select * from ')/*******************第一种方法,用游标***3w@live.cn***********************/DECLARE @RYear intdeclare @BMonth intdeclare @EMonth intdeclare @RMoney intDECLARE DateDemo_cursor CURSOR FORselect RYear,BMonth,EMonth,RMoney from @TableVar where 1=1OPEN DateDemo_cursorFETCH NEXT FROM DateDemo_cursorINTO @RYear,@BMonth,@EMonth,@RMoneyWHILE @@FETCH_STATUS = 0BEGIN----print @RYear      ----print @BMonth      ----print @EMonth      ----print @RMoney--修改记录         while(@EMonth-@BMonth>=0)begininsert INTO SELECT TOP 1 cast(RYearAS nvarchar(4))+'-'+CASE WHEN (@BMonth,RYearint not null,BMonth int not null  ,EMonth
int not null,RMoney Decimal(15,2) not null  );
insert into @TableVar(RYear ,BMonth ,EMonth ,RMoney)select * from OpenRowSet('Microsoft.Jet.OLEDB.4.0','Excel 8.0;HDR=Yes;IMEX=1;Database=D:\test\test20110501.xls','select * from ');with seq as (select top 12 row_number() over (order by object_id) valfrom sys.objects)selectcast(t.RYearAS nvarchar(4))+'-'+CASE WHEN (t.BMonth+seq.val
页: [1]
查看完整版本: 一个Excel导入SQL Server的例子