-
Notifications
You must be signed in to change notification settings - Fork 14
/
SelectFlatFiles.sql
53 lines (41 loc) · 1.3 KB
/
SelectFlatFiles.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
--#############################################################################################################
--
--Configuration
--
--#############################################################################################################
DECLARE @Filepath VARCHAR(1000) = N'\\domain\blah\blah\Mydata.txt'
DECLARE @Fieldseparator CHAR(1) = ',';
DECLARE @Rowseparator CHAR(1) = CHAR(10);
--Cleanup from previous runs
IF OBJECT_ID('tempdb..#MyTextImport') IS NOT NULL
DROP TABLE #MyTextImport;
--Create table for output
DECLARE @MyRows TABLE
(MyCol1 VARCHAR(8000)
,MyCol2 VARCHAR(8000)
,MyCol3 VARCHAR(8000)
,MyCol4 VARCHAR(8000)
);
--Build SQL
DECLARE @Generated_SQL VARCHAR(8000) = '
CREATE TABLE #MyTextImport (
MyCol1 VARCHAR(8000),
MyCol2 VARCHAR(8000),
MyCol3 VARCHAR(8000),
MyCol4 VARCHAR(8000)
);
BULK INSERT #MyTextImport
FROM ''' + @Filepath + '''
WITH (FirstRow = 1, FieldTerminator = ''' + @Fieldseparator
+ ''', RowTerminator = ''' + @Rowseparator + ''');
SELECT * FROM #MyTextImport';
--Insert data in generated table
INSERT INTO @MyRows
EXEC (@Generated_SQL
);
--Output data
SELECT *
FROM @MyRows
--Cleanup
IF OBJECT_ID('tempdb..#MyTextImport') IS NOT NULL
DROP TABLE #MyTextImport;