1

我正在尝试将 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 在每一行都在改变位置,我做错了什么?

4

2 回答 2

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,丢弃游标中的值。也许你可以澄清这条线应该做什么?

于 2013-05-18T15:42:05.580 回答
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

或者

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 查询的 where 子句的专家,但我猜有一种方法。

于 2013-05-18T22:32:24.793 回答