BULK INSERT with variable file name in SET statement - sql

I am trying to do a bulk insert but the #CSVPath is not resolving.
declare #path varchar(255)
set #path = 'C\CSVPath.csv';
BULK INSERT #mytable FROM #CSVPath <-- Error line
WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' );
I've tried
FROM ''' + #CSVpath + '''
If I hard code the path it works. If I wrap it all in a SET statement and execute it works.
declare #sql varchar(max)
set #sql = 'BULK INSERT #mytable FROM ''' + #CSVPath + ''' WITH ...
exec (#sql)
However, I cannot do it this way and need to it the first method but it doesn't seem to be resolving and cannot figure how to get it to work.

properly When running query dynamics, the compiler stores the values of the variable, but does not normally name the table or address through the variable.
BULK INSERT #mytable
FROM 'C:\test.csv'
WITH
(
FIRSTROW = 2, -- as 1st one is header
FIELDTERMINATOR = ',', -- field delimiter
ROWTERMINATOR = '\n', -- next row
TABLOCK
)

Related

bulk insert into a table from a tab-delimited text file with additional column not existed in the file

the table that im trying to insert into has an additional first column which is id that doesnt exist in the file. Below is my attempt trying to insert the record from the file(with header row) while inserting to the additional column but im getting repeated syntax error on the command
SELECT #fileName=[FileName],
#email=[Email],
#CustomerId=ImportBy,
#fullPath = 'D:test.txt'
FROM [dbo].[Log_Import]
WHERE INTID = #intId
SET #command = 'BULK INSERT [dbo].[ProcessTesting] SELECT ' + CAST(#intID AS VARCHAR(50)) +', * FROM ''' + #fullPath + ''' WITH ( FIELDTERMINATOR =''\t'', FIRSTROW = 1 )'
EXEC(#command)
You could use OPENROWSET(BULK to insert with a custom INSERT...SELECT statement.
I strongly suggest you use a format file.
SELECT #fileName=[FileName],
#email=[Email],
#CustomerId=ImportBy,
#fullPath = 'D:test.txt'
FROM [dbo].[Log_Import]
WHERE INTID = #intId
SET #command = '
INSERT [dbo].[ProcessTesting] (ID, OtherColumnsHere)
SELECT
' + CAST(#intID AS VARCHAR(50)) +',
OtherColumnsHere
FROM OPENROWSET(BULK ' + QUOTENAME(#fullPath, '''') + ', FORMATFILE = ''YourFormatFile'', FIRSTROW = 1 ) r;
';
EXEC sp_executesql #command;
Note use of QUOTENAME to escape the file name properly

BULK INSERT from variable Date Filename - ERROR

I am trying to do an insert of a text file that contain datetime in filename.
declare #V_SQL varchar(100)
set #V_SQL = (select REPLACE(REPLACE(CONVERT(VARCHAR,getdate()-1,106), ' ',''), ',',''))
BULK INSERT [dbo].[test] FROM '"E:\test_"+ #V_SQL +".txt"'
WITH
(
FIELDTERMINATOR = '|',
ROWTERMINATOR = '0x0a'
)
GO
When I run the above I get following message - BULK INSERT [dbo].[test] FROM '"E:\test_"+ #V_SQL +".txt"'
You can't put a variable or an expression there. You'll need to use dynamic SQL.
DECLARE #sql nvarchar(max) = N'BULK INSERT dbo.test FROM '''
+ 'c:\test_'
+ REPLACE(CONVERT(char(11), DATEADD(DAY,-1,GETDATE()), 13),' ','')
+ ''' WITH
(
FIELDTERMINATOR = ''|'',
ROWTERMINATOR = ''0x0a''
);';
PRINT #sql;
--EXEC sys.sp_executesql #sql;
I strongly recommend:
not using shorthand for date operations (e.g. GETDATE()-1)
always declaring lengths for variable data types like varchar.

SQL Bulk Insert in a loop

I'm trying run BULK INSERT in a loop. Loop through each file in some directory ends with no of particular file. Below is my solution
DECLARE #startFlag INT
DECLARE #endFlag INT
DECLARE #fileName varchar(50)
SET #startFlag = 1
SET #endFlag = 10
WHILE (#startFlag <= #endFlag)
BEGIN
SET #fileName = 'c:\path to file\filename_' + cast(#startFlag as varchar) + '.csv'
BULK
INSERT dbo.Intraday
FROM #fileName
WITH
(
FIELDTERMINATOR = '|',
ROWTERMINATOR = '\n'
)
SET #startFlag = #startFlag + 1
END
GO
but seems don't work. Is there anything I've overlooked or another missing stuff I can fix this issue?
You can't use variables or expressions all the places you might like in TSQL. You'll have to use dynamic SQL:
declare #fileName nvarchar(2000) = 'foo.csv'
SET #fileName = 'foo'
declare #sql nvarchar(max) = N'
BULK
INSERT dbo.Intraday
FROM '''+#fileName+'''
WITH
(
FIELDTERMINATOR = ''|'',
ROWTERMINATOR = ''\n''
)';
exec (#sql);
you can not use veritable name after From. you have to provide the name of file after from clause not variable. so you need to make complete bulk insert statement dynamically. please refer below sample code -
declare #sql nvarchar(max)
DECLARE #fileName varchar(50)
set #fileName ='C:\Input.txt'
set #sql = 'BULK
INSERT dbo.Intraday
FROM ''' + #fileName + '''
WITH
(
FIELDTERMINATOR = ''|'',
ROWTERMINATOR = ''\n''
)'
exec(#sql)

SQL Query txt file named currentdate

in brief
That:
bulk insert Table
from '**C:\PATH\ currentdate_time.txt**'
with (fieldterminator = ',', rowterminator = '\n')
is what i want to do in MSSQL.
example : 13.03.2014_15:18.txt
Something like
Declare #sql varchar(1000)
set #sql = 'Bulk insert ' + #Table + ' from ''' + #file + ''' with (fieldterminator = '','', rowterminator = ''\\n'')'
Exec(#sql)
#Table and what #File would have to come in as arguments, say to a Stored Proc, or a statement.

BULK INSERT with variable file name

i am trying to bulk insert into Db using sql server 2005
Below is the code.
declare #path varchar(500)
set #path = 'E:\Support\test.csv';
Create table #mytable( name varchar(max), class varchar(max), roll varchar(max) )
BULK INSERT #mytable FROM #path <-- Error line
WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' );
Go
select * from #mytable
drop table #mytable
Problem: issue is that my file path is dynamic and comes from a variable instead of hard coding which is not working
If i change the error line to below it works
BULK INSERT #mytable FROM 'E:\Support\test.csv';
Please advise how to fix this
Try to use Dynamic SQL:
declare #sql varchar(max)
set #sql = 'BULK INSERT #mytable FROM ''' + #path + ''' WITH ...
exec (#sql)
DECLARE #path varchar(50) = 'D:\ARQUIVOS_CARGAS\CABOS\FILE.prn'
DECLARE #SQL_BULK VARCHAR(MAX)
SET #SQL_BULK = 'BULK INSERT #TAB FROM ''' + #path + ''' WITH
(
CODEPAGE = ''ACP'',
FIRSTROW = 1,
FIELDTERMINATOR = ''tab'',
ROWTERMINATOR = ''0x0a'',
KEEPNULLS
)'
EXEC (#SQL_BULK)