仅插入某些.csv文件

时间:2014-12-11 06:38:11

标签: csv sql-server-2008-r2 bulkinsert

我正在研究SQL Server 2008 R2。

我需要BULK INSERT只有一个.CSV文件。

这是我的剧本:

BULK INSERT HPCM_HRSS.dbo.HRSS_TEST
        FROM '\\FOLDER\HRSS TEST\BISM043_Oracle FRG Workforce 201410.csv'
            WITH
    (
                FIELDTERMINATOR = ',',
                ROWTERMINATOR = '\n',
                FIRSTROW = 2
    )
GO

此命名只有一个文件,我在导入后归档此文件。 文件名从“BISM043_Oracle FRG Workforce 201410.csv”更改为“BISM043_Oracle FRG Workforce 201411.csv”

如何更改脚本以导入该特定文件夹中命名为“BISM043_Oracle FRG Workforce”的任何文件?

任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:1)

为了放大SQLCMD模式我正在谈论。这是一个定位文件的CMD批处理文件,然后调用SQLCMD:

echo on
setlocal enabledelayedexpansion
rem ---
rem this finds the latest .bak file in the backup directory
rem ---
set SQLBACKUPPATH=\\SERVER\sqlbackups\SQLSERVERNAME\DBNAME
for /F %%f in ('dir /b /o:-d !SQLBACKUPPATH!\*.bak') do set BAKFILE=!SQLBACKUPPATH!\%%f  

rem ---
rem this passes the found bak file as the parameter BAKFILE to the SQL file in SQLCMD mode
(sqlcmd -v BAKFILE ="!BAKFILE!" -i UpdateDevDBFromProdBak.sql -I -S SQLSERVER -E  -d master )

这是在最后一行调用的UpdateDevDBFromProdBak.SQL文件:

ALTER DATABASE [MyDB]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO

RESTORE DATABASE [MyDB] FROM DISK = '$(BAKFILE)'WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 5;
GO

ALTER DATABASE [MyDB] SET  RECOVERY SIMPLE
GO

ALTER DATABASE [MyDB] SET MULTI_USER WITH ROLLBACK IMMEDIATE;
GO

USE [MyDB]

EXEC sp_change_users_login 'auto_fix','mydbuser'
GO

答案 1 :(得分:0)

谢谢Ross Presser,你的回答确实引导我朝着正确的方向前进。

以下是我为了获得正确结果而做的事情:

DECLARE @SQL        nvarchar(max),
        @FileName   nvarchar(200)

        CREATE TABLE #Temp_FileName
        (
            [FileName] nvarchar(200)
        )

INSERT INTO #Temp_FileName
EXECUTE XP_CMDSHELL 'dir \\FAS-RBGFS01\costec\HRSS\ /b'

DELETE FROM #Temp_FileName
WHERE [FileName] NOT LIKE 'BISM043_Oracle FRG Workforce%'


SELECT TOP(1) @FileName = [FileName] FROM #Temp_FileName ORDER BY [FileName] DESC

SET @SQL = 'BULK INSERT HPCM_HRSS.dbo.HRSS_TEST
        FROM ''\\FAS-RBGFS01\costec\HRSS\' + @FileName + '''
            WITH
    (
                FIELDTERMINATOR = '','',
                ROWTERMINATOR = ''\n'',
                FIRSTROW = 2
    )'

EXEC (@SQL)

DROP TABLE #Temp_FileName