早上好。尝试通过一条语句获取以下查询以CSV加载数据,如果不幸失败,将不胜感激。
这是我的数据:
我正在使用的语句是:
create table #tempTablea
(
Employee_Id nvarchar(50),
First_Name nvarchar(50),
Last_Name nvarchar(50),
Japanese_Staff nvarchar(50),
Worker_Type nvarchar(50),
Hourly___Salaried nvarchar(50),
[Date] nvarchar(50),
[Start] nvarchar(50),
[End] nvarchar(50),
[Hour] nvarchar(50),
Timesheet_Start nvarchar(50),
Timesheet_End nvarchar(50),
Note nvarchar(50),
Is_Time_Off nvarchar(50),
Department_Full_Path nvarchar(50),
Called_In_Full_Path nvarchar(50),
Time_Off_Name nvarchar(50))
BULK INSERT #tempTablea FROM 'c:\data\555.csv' WITH
(
FIRSTROW = 8,
FIELDTERMINATOR = ',', --CSV field delimiter
ROWTERMINATOR = '\n', --Use to shift the control to next row
ERRORFILE = 'C:\Errors\Error.CSV',TABLOCK)
INSERT INTO Ignition.dbo.timelogtest
(Employee_Id,
First_Name,
Last_Name,
Japanese_Staff,
Worker_Type,
[Date],
[Start],
[End],
[Hourly___Salaried],
[Hour],
Timesheet_Start,
Timesheet_End,
Note,
Is_Time_Off,
Department_Full_Path,
Called_In_Full_Path,
Time_Off_Name)
select t.Employee_Id,t.First_Name,t.Last_Name,t.Japanese_Staff,t.Worker_Type,t.Hourly___Salaried,(Cast(t.[Date] as date)),(Cast(t.[Start] as datetime)), (Cast(t.[End] as datetime)),t.[Hour],(Cast(t.Timesheet_Start as date)), (CAST(t.Timesheet_End as date)), t.Note,t.Is_Time_Off,t.Department_Full_Path,t.Called_In_Full_Path,Time_Off_Name
from #tempTablea t
我得到的错误是:
(受影响的815行)消息241,级别16,状态1,第30行转换 从字符串转换日期和/或时间时失败。
所以我知道数据正在加载到临时表中,但是当我将数据加载到实际表中时,我希望它失败了,我假设它是从日期开始的转换,但是不确定我的工作方式错了。我会做平面文件,除了我每天都会收到此CSV文件外,我想将其设置为最终自动化,以便它只提取并每天运行CSV文件,而没有人与之交互。如果您能帮助我将其从temp表转换为实际表,我将非常感谢!
答案 0 :(得分:0)
在INSERT..SELECT中,将所有CAST
和CONVERT
语句替换为TRY_CAST
和TRY_CONVERT
。
答案 1 :(得分:0)
我认为这可能是俗气的,但我发现是由于转换而不是转换而导致的。如果其他人还有其他问题,请发布答案-谢谢大家的感谢。
if object_id('tempdb..#tempTablea') is not null
drop table #tempTablea
create table #tempTablea
(
Employee_Id nvarchar(50),
First_Name nvarchar(50),
Last_Name nvarchar(50),
Worker_Type nvarchar(50),
[Date] nvarchar(50),
[Start] nvarchar(50),
[End] nvarchar(50),
[Hour] nvarchar(50),
Is_Time_Off nvarchar(50),
Department_Full_Path nvarchar(50),
Time_Off_Name varchar(75))
BULK INSERT #tempTablea FROM 'c:Data\555.csv' WITH
(
FIRSTROW = 9,
FIELDTERMINATOR = ',', --CSV field delimiter
ROWTERMINATOR = '\n', --Use to shift the control to next row
ERRORFILE = 'C:\Errors\Error.CSV',TABLOCK)
INSERT INTO Ignition.dbo.timelogtest
(Employee_Id,
First_Name,
Last_Name,
Worker_Type,
[Date],
[Start],
[End],
[Hour],
Is_Time_Off,
Department_Full_Path,
Time_Off_Name)
select t.Employee_Id,t.First_Name,t.Last_Name,t.Worker_Type,
convert(date,t.[date]),convert(datetime2,t.[Start]),Convert(datetime2,t.[End]),t.[Hour], t.Is_Time_Off,
t.Department_Full_Path,t.Time_Off_Name
from #tempTablea t
where t.[date] not in (select [date] from Ignition.dbo.timelogtest)