无法将多个CSV文件导入SQL Server

时间:2017-07-27 02:03:32

标签: sql-server-2008

我想将几个.csv文件导入SQL Server,因此我使用bulk insert来执行此操作。但是,当我运行此脚本时,bulk insert仅将每个.csv文件的第一行插入到表中,而不是所有行。

我一直在调试这个问题一整天。请帮我解决这个问题。感谢

DECLARE @dir VARCHAR(100)
DECLARE @fn VARCHAR(100)
DECLARE @path VARCHAR(200)
DECLARE @ID int
DECLARE @judge int
DECLARE @sql VARCHAR(MAX)

SET @dir='D:\try\'
SET @path=''

IF OBJECT_ID('tempdb..#DirectoryTree2') IS NOT NULL
   DROP TABLE #DirectoryTree2;

CREATE TABLE #DirectoryTree2
(
     id int IDENTITY(1,1),
     fname VARCHAR(100), 
     d int,
     f int
);

INSERT INTO #DirectoryTree2 
    EXEC xp_dirtree 'D:\try\',1,1

WHILE EXISTS(SELECT fname from #DirectoryTree2)
BEGIN
     SET @sql = ''
     SET ROWCOUNT 1 --get the filename of the first row

     SELECT @ID = id, @fn = fname 
     FROM #DirectoryTree2

     SET @path = @dir + @fn

     SET @fn = REPLACE(@fn,'.csv','')
     SET @fn = REPLACE(@fn,'-','')

     SET @sql = 'CREATE TABLE [try].[dbo].'+@fn+'
     (
     ID VARCHAR(50),JLBH VARCHAR(50),HPHM VARCHAR(50),HPZL VARCHAR(50),JGSJ VARCHAR(50),CLSD VARCHAR(50),ZGXS VARCHAR(50),ZDXS VARCHAR(50),CWKC VARCHAR(50),HPYS VARCHAR(50),CLLX VARCHAR(50),JLLX VARCHAR(50),HDSJ VARCHAR(50),BZWZDM VARCHAR(50),SBBH VARCHAR(50),CDBH VARCHAR(50),FXBH VARCHAR(50),TPSL VARCHAR(50),ZFBJ VARCHAR(50),SJLY VARCHAR(50),CCLX VARCHAR(50),BZ VARCHAR(200),CSYS VARCHAR(50),JLLB VARCHAR(50),XSFX VARCHAR(50),CSBJ VARCHAR(50),TPLX VARCHAR(50),XRSJ VARCHAR(50),DEALTIME1 VARCHAR(50),DEALTIME2 VARCHAR(50),DEALTIME3 VARCHAR(50),DEALTIME4 VARCHAR(50),TXFS VARCHAR(50),WFDM VARCHAR(50)
     )'

     EXEC(@sql)

     SET @sql = 'BULK INSERT try.dbo.'+@fn+' FROM ''' + @path + ''' '
       + '     WITH ( 
               FIELDTERMINATOR = '','', 
               ROWTERMINATOR = ''\n'', 
               FIRSTROW = 2 
            ) '
     EXEC(@sql)

     SET ROWCOUNT 0

     DELETE FROM #DirectoryTree2 
     WHERE id = @ID
END

0 个答案:

没有答案