我创建一个SQL过程以从txt文件导入数据。但是,有很多文件(约80个文件),我无法列出其名称。其名称格式类似于“ DATA_XXXXXXX.TXT”
DECLARE @sql1 nvarchar(max) = N'BULK INSERT dbo.Student FROM '''
+ 'D:\NEW_FOLDER\DATA_20190222'
+ '.TXT'
+ ''' WITH
(
FIELDTERMINATOR = ''|'',
MAXERRORS = 10000
);';
EXEC sys.sp_executesql @sql1;
我希望这些文件中的所有数据都应加载到表中。我该怎么办?
答案 0 :(得分:1)
您可以使用while循环来完成此操作,将值插入到临时表中,然后使用动态SQL递增文件名变量:
CREATE TABLE #TEMP_FILENAMES
(
FILENAME VARCHAR(50)
)
INSERT INTO #TEMP_FILENAMES
VALUES('20190222')
INSERT INTO #TEMP_FILENAMES
VALUES('20190223')
DECLARE INT @YEARMMDD
WHILE EXISTS(SELECT * FROM #TEMP_FILENAMES)
BEGIN
SET @YEARMMDD = (SELECT TOP 1 FILENAME FROM #TEMP_FILENAMES)
DECLARE @sql1 nvarchar(max) = N'BULK INSERT dbo.Student FROM '''
+ 'D:\NEW_FOLDER\DATA_' + @YEARMMDD
+ '.TXT'
+ ''' WITH
(
FIELDTERMINATOR = ''|'',
MAXERRORS = 10000
);';
EXEC sys.sp_executesql @sql1;
DELETE FROM #TEMP_FILENAMES WHERE FILENAME = @YEARMMDD
END