有人提問如下:
這個是Excel的,比如是test.xls解析:
思路一:可以使用OpenRowset查詢導入到表變量中,再用游標循環賦值。方法如下:
use testdb2
go
/*******************建立測試數據***3w@live.cn***********************/
IF NOT OBJECT_ID('[TBTest]') IS NULL
DROP TABLE [TBTest]
GO
CREATE TABLE [TBTest](
[tid] int identity(1,1) PRimary key,
[date] NVARCHAR(20) null,
[Money] 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
--------go
use testdb2
go
/*******************定義表變量***3w@live.cn***********************/
Declare @TableVar table
(PKId int primary key identity(1,1)
,RYear int 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 [Sheet1$]')
/*******************第一種方法,用游標***3w@live.cn***********************/
DECLARE @RYear int
declare @BMonth int
declare @EMonth int
declare @RMoney int
DECLARE DateDemo_cursor CURSOR FOR
select RYear,BMonth,EMonth,RMoney from @TableVar where 1=1
OPEN DateDemo_cursor
FETCH NEXT FROM DateDemo_cursor
INTO @RYear,@BMonth,@EMonth,@RMoney
WHILE @@FETCH_STATUS = 0
BEGIN
----print @RYear
----print @BMonth
----print @EMonth
----print @RMoney
--修改記錄
while(@EMonth-@BMonth>=0)
begin
insert INTO [TBTest]
SELECT TOP 1 cast(RYear AS nvarchar(4))+'-'+
CASE WHEN (@BMonth<10) THEN '0'+cast(@BMonth AS nvarchar(2))
ELSE cast(@BMonth AS nvarchar(2)) END,
Rmoney from @TableVar where Ryear=@RYear
SET @BMonth=@BMonth+1
end
--修改結束
FETCH NEXT FROM DateDemo_cursor into @RYear,@BMonth,@EMonth,@RMoney
END
CLOSE DateDemo_cursor
DEALLOCATE DateDemo_cursor
GO
SELECT * FROM [TBTest]
新聞熱點
疑難解答