将Excel导入SQL时无限循环

时间:2013-05-18 21:16:02

标签: sql excel import

  

我有这个代码

USE [DATABASE]
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 @Box,@Code,@Validity

WHILE @@FETCH_STATUS = 0
begin

Insert into Cards (Box, BarCode, ValidityDate) 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$]')
fetch next from c into @Box,@Code,@Validity

end

CLOSE c
DEALLOCATE c


end
  

导出到表“Cards”时,空行也会被复制到表中,并且进程不会停止,循环会一直打开并且一遍又一遍地重新启动进程,查询不会停止执行除非我停止它,当我看到表的内容时,我看到空行的NULL值和填充的行的值,并且它们被重复,所以如何停止查询读取空行并阻止它读取excel文件一遍又一遍?

3 个答案:

答案 0 :(得分:1)

试试这个循环:

WHILE @@FETCH_STATUS = 0
begin

Insert into Cards (Box, BarCode, ValidityDate)
    select @Box, @Code , @Validity;

fetch next from c into @Box,@Code,@Validity

end;

您的原始代码同时使用游标并直接在from语句中获取。这个版本只使用光标。

答案 1 :(得分:0)

为什么不使用这样的东西而不是光标

INSERT INTO (Box, BarCode, ValidityDate) 
SELECT *
  FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=C:\Barcodes.xlsx;HDR=YES', 
           'SELECT Box, Code, Validity FROM [sheet1$]')

答案 2 :(得分:-2)

我使用了Task - > Import data选项将数据从excel传输到sql,并且获得了无限循环。我关闭了SQL Server管理工作室并重试了相同的选项,它对我有用。