T-SQL跳过损坏的CSV加载语句?

时间:2018-04-17 09:30:48

标签: sql tsql corrupt openrowset

我目前有一个脚本,使用OPENROWSET将数据从多个文件加载到临时表中。偶尔我会遇到一个损坏的文件,并希望脚本能够继续,如果找到它而不是失败。 例如:

 SELECT
 CAST(F1 as datetime)               as imported_at
, CAST(F2 as nvarchar(255))         as updated
, CAST(F3 as datetime)              as updated_at
, CAST(F4 as nvarchar(255))         as update_file
  INTO Temp
  FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel8.0;HDR=NO;Database=C:\Users\Administrator.WIN-T1K614N8PK3.001\Desktop\TV\file.xlsx','select * from [Tabelle1$]')

  SELECT
  CAST(F1 as datetime)              as imported_at
, CAST(F2 as nvarchar(255))         as updated
, CAST(F3 as datetime)              as updated_at
, CAST(F4 as nvarchar(255))         as update_file
  INTO Temp1
  FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel8.0;HDR=NO;Database=C:\Users\Administrator.WIN-T1K614N8PK3.001\Desktop\TV\file1.xlsx','select * from [Tabelle1$]')

如果第一个文件因为损坏而无法打开,我希望脚本继续。

感谢您的建议!

1 个答案:

答案 0 :(得分:0)

尝试使用try / cath块......

begin try
 SELECT
 CAST(F1 as datetime)               as imported_at
, CAST(F2 as nvarchar(255))         as updated
, CAST(F3 as datetime)              as updated_at
, CAST(F4 as nvarchar(255))         as update_file
  INTO Temp
  FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel8.0;HDR=NO;Database=C:\Users\Administrator.WIN-T1K614N8PK3.001\Desktop\TV\file.xlsx','select * from [Tabelle1$]')
end try
begin catch
end catch

begin try
  SELECT
  CAST(F1 as datetime)              as imported_at
, CAST(F2 as nvarchar(255))         as updated
, CAST(F3 as datetime)              as updated_at
, CAST(F4 as nvarchar(255))         as update_file
  INTO Temp1
  FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel8.0;HDR=NO;Database=C:\Users\Administrator.WIN-T1K614N8PK3.001\Desktop\TV\file1.xlsx','select * from [Tabelle1$]')
end try
begin catch
end catch