批量插入文件名与SQL Server类似

时间:2014-05-26 11:03:12

标签: sql-server bulkinsert

我的PRODUCTION文件夹中有三个文件。文件名将与当前日期连接。例如PRODFILE1_01052014PRODFILE2_01052014等。每日文件将与当前日期一起放置。我需要每天写一个SP到BULK INSERT文本文件。我可以写下面的脚本来批量插入一个特定的日期文件。我如何选择包含PRODFILE的所有文件?

BULK INSERT PRODFILES FROM 'D:\PRODUCTION\PRODFILE1_01052014.TXT'
WITH (FIELDTERMINATOR ='|',ROWTERMINATOR = '\n')

我需要这样的内容Like PRODFILE1*.txtLike PRODFILE2*.txt

2 个答案:

答案 0 :(得分:1)

您需要列出PRODUCTION文件夹中的所有文件,以便您可以按名称过滤文件。看看这里:How to list files inside a folder with SQL Server

答案 1 :(得分:0)

因此,您似乎正在尝试自动查看PRODUCTION文件夹,BULK INSERT最新的"今天"文件?

我认为您正在寻找类似的内容....

-- load up all the files in your PRODUCTION folder into a variable
DECLARE @BackupDirectory SYSNAME = 'C:\PRODUCTION\\'  -- remove the extra slash from the path! This is so the StockOverflow color formatting works properly on the page.
DECLARE @allFiles AS TABLE(fName varchar(500), d INT, f INT)
DECLARE @fileToImport AS VARCHAR(500)
INSERT INTO @allFiles
EXEC master.sys.xp_DirTree @BackupDirectory, 10, 1

-- get today's file suffix i.e.: {01052014} or whatever the date is today
DECLARE @dateSuffix AS CHAR(8)
SET @dateSuffix = CAST(RIGHT(CONCAT('00', DATEPART(dd, getdate())), 2) AS CHAR(2)) 
+ CAST(RIGHT(CONCAT('00', DATEPART(mm, getdate())), 2) AS CHAR(2))
+ CAST(DATEPART(yy, getdate()) AS CHAR(4))
SELECT @dateSuffix

DECLARE @i AS INT
SET @i = 1

-- loop through the files one by one and execute the bulk insert.
WHILE @i <= (SELECT COUNT(*) FROM @allFiles WHERE fName LIKE '%'+@dateSuffix)
BEGIN
   SELECT TOP 1 @fileToImport = fName FROM @allFiles WHERE fName LIKE '%'+@dateSuffix+'%' ORDER BY fName -- filter on the today's files only

   BULK INSERT [myDb].[mySchema].[myTable] 
      FROM 'C:\PRODUCTION\\' + @fileToImport + '' -- remove the extra slash from the path! This is so the StockOverflow color formatting works properly on the page.
         WITH (FIELDTERMINATOR ='|',ROWTERMINATOR = '\n')

   DELETE FROM @allFiles WHERE fName = @fileToImport -- remove processed file from the table variable

   SET @i = @i + 1
END

注意:我没有时间对此进行测试,我认为你可能需要使用游标而不是我的WHILE循环,但理论上这应该会给你一些想法。