Variables in MS SQL Bulk Insert path string - sql

I need to import 30 .csv files into an MS SQL SERVER database. I can use BULK INSERT, but because of the number of files I want to do it with loop. Each file is named as DP(1).csv, DP(2).csv, DP(3).csv, ..., DP(30).csv.
I did write a WHILE loop and with a counter that can also be used to identify a file name, but I have problems with the syntax when including the counter variable in the path name. Here is my code:
DECLARE #COUNT INT
SET #COUNT = 1
USE Db_Pc
WHILE #COUNT <= 30
BEGIN
BULK INSERT acks FROM 'C:\Users\JASON SAMUELS\Documents\M-DD\DP('+#COUNT+').csv'
WITH(FIRSTROW = 2,
ROWTERMINATOR = '\n',
FIELDTERMINATOR = ',')
SET #COUNT = #COUNT + 1
END
The error seems to be at the first + just before the variable #COUNT in the path string. This is the error message i get:
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '+'.
Msg 319, Level 15, State 1, Line 8
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
How should i insert the variable in the string?

it's because you are concatenating an int to a string.
you need to use CAST( #COUNT as varchar(X) ) (or is it CONVERT?).
try:
BULK INSERT acks FROM 'C:\Users\JASON SAMUELS\Documents\M-DD\DP(' + CAST(#COUNT as varchar(5) ) + ').csv' WITH(FIRSTROW = 2, ROWTERMINATOR = '\n', FIELDTERMINATOR = ',')
Sorry I'm not around a place I can test the exact syntax.

Related

How can I insert text, from a subquery, in a function request

I'm using a function on the Master database (xp_fileexist) to check if a folder is empty or not. If it's empty I want a 0, otherwise a 1.
If I hardcode the folder name ('C:\Import\2016-01-01\Transaction') it works fine. What doesn't work for me, is having the date as a variable, as the date changes from time to time. For the variable, I use this:
'C:\Import\The Netherlands\'+CAST((select workingdate from system..tmpworkingdate) AS VARCHAR(10))+'\Transaction(BP)'
This is the code I've tried:
CREATE TABLE #temp (FileExists int, IsDirectory int, ParentDirExists int)
INSERT INTO #temp
EXEC master..xp_fileexist ('C:\Import\'+CAST((select workingdate from system..tmpworkingdate) AS VARCHAR(10))+'\Transaction(BP)')
IF EXISTS(SELECT IsDirectory FROM #temp WHERE IsDirectory=1)
PRINT 1
ELSE
PRINT 0
DROP TABLE #temp
Error: Msg 102, Level 15, State 1, Line 5 Incorrect syntax near
'C:\Import\The Netherlands\'. Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'AS'.
Does anyone have a clue?
EXEC doesn't allow string manipulations (or any expression evaluation). Define the value beforehand:
DECLARE #filename VARCHAR(MAX);
SET #filename = 'C:\Import\'+CAST((select workingdate from system..tmpworkingdate) AS VARCHAR(10))+'\Transaction(BP)';
EXEC master..xp_fileexist (#filename);
That said, you should use CONVERT() or FORMAT() to be sure you get the format you really want. You wouldn't want system changes to totally break this code.
EDIT:
Argg! I didn't realize that EXEC master..xp_fileexist doesn't even allow string variables on the execution line. So, you have to do the whole thing as dynamic SQL:
DECLARE #sql NVARCHAR(MAX) = 'EXEC master..xp_fileexist ''' + #filename + '''';
EXEC(#sql);
(There are examples on the web that do use variables, so maybe this depends on the SQL Server version.)

Syntax error in sql exec count

declare #message int,#DBName varchar(50)
set #DBName ='AutoChip'
exec('select '+#message+'= count(*) from '+#DBname+'.[dbo].[Report List]')
print #message
Getting an error trying to print the count
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.
I will pass DBname dynamically, I am using a cursor
The variable name needs to be part of dynamic SQL you are creating, but it's shouldn't be concated with it.
For example, if your variable is of type varchar and has value as 'ERROR', resultant query will be
select ERROR= count(*) from YOURDBNAME.[dbo].[Report List]
so the correct one is below.
exec('select #message= count(*) from '+#DBname+'.[dbo].[Report List]')
You need to include variable declaration and initialization in dynamic sql. You cannot set a value of external variable inside a dynamic sql as the context of execution will be different.

SQL on SQL Server- unable to run query which is stored in variable and executed using exec

I am trying to execute the following SQL in SQL Server 2008-
DECLARE #sql nvarchar, #fullname nvarchar;
SET #fullname='1patents_corrected.csv';
SET #sql = 'BULK INSERT GooglePatentsIndividualDec2012.dbo.patent from ' + #fullname+ ' WITH ( DATAFILETYPE = "char", FIELDTERMINATOR = "^", ROWTERMINATOR = "\n" );'
EXEC(#sql)
However I am getting this error--
Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure 'B'.
What am I doing wrong here?
UPDATE-- I changed the query viz. specified a size for each varchar variable. Now the code is like this--
DECLARE #MyCounter int;
DECLARE #Fileprefix nvarchar(1000), #Filesuffix nvarchar(1000), #fullname nvarchar(1000), #Counter_string nvarchar(1000), #sql nvarchar(1000);
SET #MyCounter = 1;
SET #Fileprefix= 'C:\Arvind_gpd\patents\';
SET #Filesuffix='data_corrected.csv';
WHILE (#MyCounter < 10)
BEGIN;
Set #Counter_string= Cast(#MyCounter AS varchar(1) );
Set #fullname = (#Fileprefix+ #Counter_string + #Filesuffix );
SET #sql = 'BULK INSERT GooglePatentsIndividualDec2012.dbo.patent from ' + #fullname+
' WITH ( DATAFILETYPE = "char", FIELDTERMINATOR = "^", ROWTERMINATOR = "\n" );'
EXEC(#sql);
SET #MyCounter = #MyCounter + 1;
END;
GO
However I am now getting a different error--
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'C:'.
Msg 319, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Now what am I doing incorrectly :( ?
change
DECLARE #sql nvarchar
to
DECLARE #sql nvarchar(2000)
by default the size is 1
The same applies to #fullname nvarchar; give it a size
You need to quote the file name when using BULK INSERT.
Change
SET #sql = 'BULK INSERT GooglePatentsIndividualDec2012.dbo.patent
from ' + #fullname+
WITH ( DATAFILETYPE = "char", FIELDTERMINATOR = "^", ROWTERMINATOR ="\n" );'
to
SET #sql = 'BULK INSERT GooglePatentsIndividualDec2012.dbo.patent
FROM ''' + #fullname + '''
WITH ( DATAFILETYPE = ''char'', FIELDTERMINATOR = ''^'', ROWTERMINATOR =''\n'' )'
You'll notice that I have instances of multiple single quotes bunched together. Double single quotes stand for escape in SQL Server (ie. I am quoting a quote within another quote).
Also, I see you use a lot of semicolons in your code. No need to put them in when you are writing in T-SQL

Error in reading CSV file

I am using the below code in SP, SQL Server 2005
declare #path varchar(500)
set #path = 'E:\Support\test.csv';
print #path
Create table #mytable(
name varchar(max), class varchar(max), roll varchar(max)
)
BULK INSERT #mytable FROM #path
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
);
Go
select * from #mytable
drop table #mytable
But it is throwing the following error :
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '#path'.
Msg 319, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'with'.
If this statement is a common table expression or an xmlnamespaces clause,
the previous statement must be terminated with a semicolon.
Msg 208, Level 16, State 0, Line 1
Invalid object name '#mytable'.
Could anybody help me.
You can't do the following
BULK INSERT #mytable FROM #path
if you are expecting this to translate to
BULK INSERT #mytable FROM 'E:\Support\test.csv'
It's not the file name that's in the varchar, SQL sees it #Path as the data and not a string containing the path.
If you need to use a variable for the path, you will need to use some dynamic SQL which roughly translates to (excuse syntax errors)
DECLARE #SQL varchar(max)
SET #SQL = 'BULK INSERT #mytable FROM '+ #path + '
--Add the rest of your code here
EXEC (#SQL)
If your variable is never going to change though I'd just go ahead and stick the string into the statement itself.
Hope that helps.

how to pass tablename as parameter in sql server

hello frnds i need to pass a table name as parameter to stored procedure
CREATE PROCEDURE six #tablename nvarchar
AS
SELECT * FROM + #tablename
Go
exec six Entry_sixsigma_mag
it gives error like
Msg 102, Level 15, State 1, Procedure six, Line 3
Incorrect syntax near '+'.
Msg 208, Level 16, State 1, Procedure six, Line 3
Invalid object name '#sixsigma'.
Try something like
CREATE PROCEDURE six #tablename nvarchar(100)
AS
EXEC('SELECT * FROM ' + #tablename)
Go
exec six Entry_sixsigma_mag
Have a look at EXECUTE (Transact-SQL)
But you should also have a look at
SQL Injection
Dynamic SQL & SQL injection
before using this blindly.