Using dynamic sql in openrowset produces error - sql-server

I need to create a stored procedure that gets a path as a parameter and inserts from file into table via OPENROWSET command.
After lots of searching and trying, I learned that OPENROWSET does not
support parameters and thus needs to be called with dynamic SQL.
That is the part that doesn't work, it shows me a strange error.
It could be caused by the OPENROWSET not accepting the string parameter
but - I saw many code snippets that are built similarly and users say they work.
Please help me understand what I'm missing here and how do I make this work?
Here is my code:
Declare #string varchar(MAX) = 'C:\Users\akoga_000\Desktop\test1.xlsx'
DECLARE #sqlString AS varchar(MAX)=
'insert into gameIt_DBSummer.dbo.tblUser
select * from openrowset(
''Microsoft.ACE.OLEDB.12.0'',
''EXCEL 12.0;DataBase=''
'+cast(#string as varchar(max))+'
'';Extended Properties="EXCEL 12.0 Xml;HDR=YES'',
''SELECT * FROM [Sheet1$]''
)';
EXEC (#sqlString)
//I tried also with EXEC sp_executesql and a nvarchar variable among other options
Here is the error:
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near 'C:'.

I think you are getting that error because you need double extra '' character surrounding the path (#string variable). Try this:
Declare #string varchar(MAX) = 'C:\Users\akoga_000\Desktop\test1.xlsx'
DECLARE #sqlString AS varchar(MAX)=
'insert into gameIt_DBSummer.dbo.tblUser
select * from openrowset(
''Microsoft.ACE.OLEDB.12.0'',
''EXCEL 12.0;DataBase=''''
'+#string+'
'''';Extended Properties="EXCEL 12.0 Xml;HDR=YES'',
''SELECT * FROM [Sheet1$]''
)';
select #sqlString

Related

SQLServer: Dynamic sql raise exception Could not find stored procedure

This is my dynamic sql.
DECLARE #SQL varchar(MAX)
DECLARE #Data varchar(MAX)
SET #Data='ALFKI'' OR ContactName=''Ana Trujillo'''
SET #SQL='select * from Customers Where CustomerID='''+#Data+''
print #SQL
exec (#SQL)
when i print then i get this sql select * from Customers Where CustomerID='ALFKI' this sql is right one but when i replace print #SQL with exec #SQL and execute the dynamic sql again then i am getting error called
Msg 2812, Level 16, State 62, Line 8 Could not find stored procedure
'select * from Customers Where CustomerID='ALFKI''.
not clear where i made the mistake. please give me some hint where is the problem in above dynamic sql. thanks
There is EXEC to execute a stored procedure. Of course there is no SP with the name select * from Customers....
And there is EXEC(), a function!, which is used to execute dynamically created statements.
Just use EXEC(#SQL) instead.
Another way with some more options is sp_executesql with wide support for parameters. You can use this to pass the ALFKI as parameter. Otherwise you might be open for SQL injection...

SQL variable for Database Name

I am trying to pass a database name in as a parameter and execute some dynamic SQL. As a test I created this:
declare #HRMSDatabase_1 nvarchar(50) = N'FirstDatabase',
#Example_1 nvarchar(max) =
'select #HRMSDatabase'
execute sp_executesql #Example_1, N'#HRMSDatabase nvarchar(50)', #HRMSDatabase_1
which returns FirstDatabase as I expected.
When I try this:
declare #HRMSDatabase_2 nvarchar(50) = N'FirstDatabase',
#Example_2 nvarchar(max) =
'select
''Test''
from
#HRMSDatabase.dbo.hrpersnl hp'
execute sp_executesql #Example_2, N'#HRMSDatabase nvarchar(50)', #HRMSDatabase_2
I get an error message:
Msg 102, Level 15, State 1, Line 29
Incorrect syntax near '.'.
Is what I am trying to do possible? I cannot simply use a USE FirstDatabase as I have a few databases I have to query in the same dynamic SQL using inner joins.
Also, I cannot use SQLCMD as this script gets executed from a GUI.
Basically, I don't believe you can parameterize the database name in the table specifier. Instead try this,
DECLARE #HRMSDatabase NVARCHAR(50) = N'FirstDatabase';
DECLARE #Example3 NVARCHAR(MAX) ='SELECT
''Test''
FROM
' + QUOTENAME(#HRMSDatabase) + '.[dbo].[hrpersnl] hp';
EXEC sp_executesql #Example3;
As you'll note, it's important that the #HRMSDatabase is not recieved from user input as this would be susceptible to injection attacks.

OPENROWSET: sp_executesql statement failing at #param

I am developing a program to pull in the XML file that WordPress enables you to download (essentially a backup copy).
At this point I was automating the process to allow frequent backup of my data on SQL Server, and for some reason I am stuck at developing the query to run the OPENROWSET where the XML file will be located.
DECLARE #SQL NVARCHAR(MAX)
DECLARE #ParamDefinition NVARCHAR(500) = N'#fstring NVARCHAR(MAX)'
DECLARE #string VARCHAR(MAX) =
N'C:\[FilePath]\Reviews\thehesperian2016-07-29.xml'
SET #SQL =
N'INSERT INTO #Temp (Extract_Date, XMLDATA)
SELECT GETDATE()
, A.*
FROM OPENROWSET(BULK #fstring, SINGLE_BLOB, CODEPAGE = ' + '''RAW''' + ') AS A'
EXEC sp_executesql #SQL
, #ParamDefinition
, #fstring = #string
The error:
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '#fstring'.
I can turn this into a simple query on a table in the predicate, so I have reason to suspect it is the way the filepath is read.
I've spent a few hours racking my brain trying to figure out why this is wrong. While I COULD use QUOTENAME as in this example in the BULKINSERT, I was hoping to embed all of that in the dynamic SQL (thus still use sp_executesql)
What or why am I doing this wrong? Any help will be greatly appreciated.
- Regards,
ANSWER
OPENROWSET - MSDN declares in its own paragraph:
OPENROWSET does not accept variables for its arguments.
QUOTENAME is sufficient, although I did run a few minor REPLACEfunctions anyways.
The data file path the OPENROWSET function does not allow a parameter. Instead, build the needed string with the literal:
DECLARE #string varchar(MAX) = N'C:\[FilePath]\Reviews\thehesperian2016-07-29.xml';
DECLARE #SQL nvarchar(MAX);
SET #SQL =
N'INSERT INTO #Temp (Extract_Date, XMLDATA)
SELECT GETDATE()
, A.*
FROM OPENROWSET(BULK ' + QUOTENAME(#string, '''') + ', SINGLE_BLOB, CODEPAGE = ''RAW'') AS A';
EXEC sp_execute #SQL;
--EXECUTE(#SQL);
UPDATE:
Added QUOTENAME in case the provided file path is from an untrusted source. Also, note that OPENROWSET queries are not autoparameterized. It makes no difference whether one executes the query with sp_executesql or EXECUTE here.

SQL server create stored procedure syntax error

I am trying to create a simple stored procedure:
CREATE PROCEDURE SP_Test #FilePath int
AS
SELECT
LastName, FirstName
INTO
tmp_tblPerson
FROM
OPENROWSET('MSDASQL','Driver={Microsoft Access Text Driver (.txt, .csv)}','SELECT * FROM ' + #FilePath + "'")
GO
But I get a syntax error which I don't understand..?
Msg 102, Level 15, State 1, Procedure SP_Test, Line 12
Incorrect syntax near '+'.
Any ideas?
You can't use dynamic SQL when using using OPENROWSET. A workaround is to make the entire block use dynamically created SQL like this:
CREATE PROCEDURE SP_Test #FilePath int
AS
DECLARE #sql NVARCHAR(MAX) =
'SELECT LastName, FirstName
INTO tmp_tblPerson
FROM OPENROWSET(
''MSDASQL'',
''Driver={Microsoft Access Text Driver (.txt, .csv)}'',
''SELECT * FROM '' + #FilePath)'
EXEC(#sql)
As always with dynamic SQL, make sure you are not vulnerable to SQL injection attacks.
Additionally, your query appears to be incorrect as I doubt you have a table with an integer as a name.
#filepath is int, you probably want something like
'SELECT * FROM ' + convert(varchar,#FilePath)

Use Parameter In OPENROWSET Sql Server

I am creating an stored procedure in which I am calling an another
stored procedure(This procedure is returned lot of columns and I want
only one column value So I can't create temp table to store values)
using OPENROWSET.
When I am use following then it's alright
declare #AgencyID int=15,#PatientID int=3701
SELECT a.PrimaryInsuredName
FROM OPENROWSET('SQLNCLI',
'Server=ServerName;Database=DbName;Trusted_Connection=yes',
'exec USP_Billing_GetPatientWithInsurence 3701,15') AS a;
It's working fine. But I want to pass parameters for calling
USP_Billing_GetPatientWithInsurence because values will be dynamic.
So I use following code
declare #AgencyID int=15,#PatientID int=3701
SELECT a.PrimaryInsuredName
FROM OPENROWSET('SQLNCLI',
'Server=ServerName;Database=DbName;Trusted_Connection=yes',
'exec USP_Billing_GetPatientWithInsurence '+ #PatientID +','+ #AgencyID+'') AS a;
But it's not working When I run this query then an error occurred
Incorrect syntax near '+'. I don't know why this is coming. Please
provide a solution to this. I googled also for this but can't found a
proper solution.
Thanks
You have to make your entire SELECT string dynamic:
declare #AgencyID int=15,#PatientID int=3701
DECLARE #SQLStr varchar(max)='
SELECT a.PrimaryInsuredName
FROM OPENROWSET(''SQLNCLI'',
''Server=ServerName;Database=DbName;Trusted_Connection=yes'',
''exec USP_Billing_GetPatientWithInsurence '+ CAST(#PatientID AS varchar(15)) +','+ CAST(#AgencyID AS varchar(15)) +''') AS a';
EXECUTE(#SQLStr);

Resources