我正在尝试将excel文件导入SQL,该文件有3列:Box - Code - Validity 我正在使用以下查询
USE [Libatel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetDataExcel]
as
DECLARE c CURSOR FOR select Box, Code , Validity FROM
OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\Barcodes.xlsx;HDR=YES', 'SELECT Box, Code , Validity FROM [sheet1$]')
declare @Code as bigint
declare @Box as bigint
declare @Validity as date
begin
open c
fetch next from c into @Code,@Box,@Validity
WHILE @@FETCH_STATUS = 0
begin
select @Box = Box,@Code = BarCode,@Validity =ValidityDate from Cards
Insert into Cards (BarCode,Box,ValidityDate) values (@Box,@Code,@Validity)
fetch next from c into @Box,@Code,@Validity
end
CLOSE c
DEALLOCATE c
end
我正在接受以下内容
11155232026 1 2013-05-18
1 11155232026 2013-05-18
...
...
这是第一行,Box和Code正在改变每一行的位置,我做错了什么?
答案 0 :(得分:3)
您的第二个fetch
列顺序错误:
fetch next from c into @Code,@Box,@Validity
...
fetch next from c into @Box,@Code,@Validity
另一个问题是这句话:
select @Box = Box,@Code = BarCode,@Validity =ValidityDate from Cards
有效地从Cards
表中提取一个随机行,丢弃光标中的值。也许你可以澄清这条线应该做什么?
答案 1 :(得分:1)
declare @Holder table ( ColumnA varchar(24) , ColumnB varchar(32) , ColumnEtcEtc varchar(64))
Insert into @Holder (ColumnA, ColumnB, ColumnEtcEtc ) select Box, Code , Validity FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\Barcodes.xlsx;HDR=YES', 'SELECT Box, Code , Validity FROM [sheet1$]')
Delete From @Holder where DATALENGTH(LTRIM(RTRIM(ColumnB))) <=0
OR
Insert into @Holder (ColumnA, ColumnB, ColumnEtcEtc ) select Box, Code , Validity FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\Barcodes.xlsx;HDR=YES', 'SELECT Box, Code , Validity FROM [sheet1$] where ColumnA = 2 ')
我不是excel查询子句的专家,但我猜有办法。