我想将多个csv文件插入sqlserver
表。我有一个这样做的程序。它工作,但我的所有文件都有相同的列名。因此,不是导入所有记录,而是导入第一行的列名。如果我手动删除第一行然后导入其他记录,我有数千个文件,所以我不能手动工作。我在这里发布商店程序。请告诉我,我是否可以改变一些东西来使这项工作。
ALTER procedure [dbo].[usp_ImportMultipleFiles] @filepath varchar(500),
@pattern varchar(100), @TableName varchar(128)
as
set quoted_identifier off
declare @query varchar(1000)
declare @max1 int
declare @count1 int
Declare @filename varchar(100)
set @count1 =0
create table #x (name varchar(200))
set @query ='master.dbo.xp_cmdshell "dir '+@filepath+@pattern +' /b"'
insert #x exec (@query)
delete from #x where name is NULL
select identity(int,1,1) as ID, name into #y from #x
drop table #x
set @max1 = (select max(ID) from #y)
--print @max1
--print @count1
While @count1 <= @max1
begin
set @count1=@count1+1
set @filename = (select name from #y where [id] = @count1)
set @Query ='BULK INSERT '+ @Tablename + ' FROM '''+ @Filepath+@Filename+'''
WITH ( FIELDTERMINATOR = '','',ROWTERMINATOR = ''\n'')'
--print @query
exec (@query)
insert into logtable (query) select @query
end
drop table #y
答案 0 :(得分:1)
您可以在批量插入语句中使用第一行选项,例如......
BULK INSERT Table_Name
FROM 'C:\FilePath'
WITH
(
FIELDTERMINATOR = ','
,ROWTERMINATOR = '\n'
,FIRSTROW = 2 --<-- This option here
)
编辑您的搜索
DECLARE @Query NVARCHAR(MAX);
SET @Query = N'BULK INSERT '+ @Tablename +
N' FROM '''+ @Filepath+@Filename +
N''' WITH ( FIELDTERMINATOR = '',''
,ROWTERMINATOR = ''\n''
,FIRSTROW = 2
)'