有什么简单的方法可以将多个 .txt 文件导入 SQL 服务器?

Is there any easy way to import multiple .txt files to SQL server?

我正在尝试将 24 个 .txt 文件导入服务器,但我的权限有限。所有文件都以相同的字符开头,但“*”此掩码不能用于此查询。我使用下面的脚本。

    SELECT * into TABLE
FROM OPENROWSET( BULK 'c:\path\files\good*.txt', FORMATFILE = 'c:\path\files\import.xml',FIRSTROW = 2) AS DATA;

您需要先创建 table,然后使用循环插入每个文件。

创建目标后尝试以下脚本 table:

declare @filepath varchar(100)= 'c:\path\files\'
    ,@pattern varchar(100)= 'good*.txt'
    ,@TableName varchar(100)= 'TestTable'

DECLARE @query varchar(1000)
DECLARE @numfiles int
DECLARE @filename varchar(100)
DECLARE @files TABLE (SourceFileName varchar(200) NULL)

SET @query = 'master.dbo.xp_cmdshell "dir ' + @filepath+@pattern + ' /b"'
INSERT @files(SourceFileName) 
EXEC (@query)

DECLARE CUR CURSOR FAST_FORWARD FOR
SELECT SourceFileName FROM @files WHERE SourceFileName IS NOT NULL

SET @numfiles =0
OPEN CUR
FETCH NEXT FROM CUR INTO @filename
WHILE (@@FETCH_STATUS = 0)
BEGIN
    print @filename
    SET @numfiles+=1

    SET @query = ('BULK INSERT ' + @TableName
                    + ' FROM ''' + @Filepath+@filename + ''' WITH(
                        FORMATFILE = ''c:\path\files\import.xml'',
                        FIRSTROW = 2
                        );'
              )
    PRINT @query
    EXEC (@query)

    FETCH NEXT FROM CUR INTO @filename
END

CLOSE CUR
DEALLOCATE CUR