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);
Related
sorry I am uploading a pic of my query as I dont know to format my text...as a newbie its confusing.
So you want to execute:
select * from File_20170703 -- where your table name is a variable.
It is not possible to use variables for table or column names, what you need to do is to build a dynamic sql and execute it using sp_executesql.
here is an example:
DECLARE #sql nvarchar(4000)
SELECT #sql = 'SELECT * FROM File_20170703'
EXEC sp_executesql #sql
More info about dynamic sql
A simple TSQL "dynamic sql" looks like this:
DECLARE #file_name AS VARCHAR(100)
DECLARE #query AS VARCHAR(MAX)
SET #file_name = 'file_20170101'
SET #query = 'SELECT * FROM ' + #file_name
execute(#query)
Basically you need to create a valid sql query by concatenating various parts of the query together, then you can execute that whole big string as your query.
You can use SQL Cursor along with while loop. Examples are given here:
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/while-transact-sql
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
Is it natural that SQL Server does not catch objects dependencies in stored procedures through dynamic SQL:
CREATE PROCEDURE testSp (#filter nvarchar(max)) AS
exec ('select * from testTable where 1=1 AND '+ #filter)
Here SQL Server will not detect dependency between testTable and testSp.
What kind of "advice" do you have for the DBMS? I propose it could be very "cheap query" :
CREATE PROCEDURE testSp (#filter nvarchar(max)) AS
-- cheap query like 'select top 1 #id=id from testTable'
exec ('select * from testTable where 1=1 AND '+ #filter)
So the question is which queries could be good candidates for that purpose?
P.S. Of course I expect that they all will have their minuses..
When using dynamic SQL the query parts that are tekst (between quotes) are not detected as code by the IDE or the engine until the moment they are excuted. So this answers your first question, yes it is natural.
The only way around this that I can think of is to create a view using the generated output of the dynamic sql and check if the view definition is still valid at any point you want to check if the procedure is valid.
Usually when you need to do something like this there is an earlier departure from standard methods that if handled removes the need for such silly tricks.
Example:
USE demo
GO
DECLARE #sql NVARCHAR(MAX) = '
SELECT firstname, lastname FROM dbo.employees'
DECLARE #view NVARCHAR(MAX) = '
CREATE VIEW dbo.test_view
AS ' + #sql
EXEC sp_executesql #view
BEGIN TRY
DECLARE #validation int = (SELECT TOP 1 COUNT(*) FROM demo..test_view)
EXEC sp_executesql #sql
END TRY
BEGIN CATCH
PRINT 'Dynamic SQL out of date'
END CATCH
SET NOEXEC ON
select * from testTable
SET NOEXEC OFF
do the job: code really not executed, but dependecy is declared.
Can I pass a variable to a SELECT statement?
I keep getting an error message saying I need to declare it.
However, it is declared.
SELECT (list of columns)
FROM #database_table
You are looking to use Dynamic SQL to perform this type of query.
The Curse and Blessings of Dynamic SQL
Here is a quick sample
declare #sqlstatement nvarchar(4000)
declare #table sysname
set #table = 'yourTableName'
set #sqlstatement = 'SELECT * FROM ' + QUOTENAME(#table)
exec(#sqlstatement)
Yes, use dynamic sql statements to build your select statement.
-- Procedure input parameters
#TableName varchar(50)
-- Query guts
Declare #sql varchar(2000)
Set #sql = 'Select columnname from ' + #TableName
exec (#sql)
The one time you can do what you want is when you use table variables. You have to define the variables as:
declare #name table (<column list>)
This is alternative method of declaring a temporary table.
Other than this, I fully agree with bluefeet. You should read the link he posted.
I have created a Temp table(#TempTable). I am trying to insert the date to get but I am getting an error. It's a dynamic query.
I am trying to get the date from another table and inserting the date to temp table
Just to make sure you understand the problem I have given an example
DECLARE #OfferEndDateTime datetime
SELECT #OfferEndDateTime = getdate()-1
print #VOfferEndDateTime
DECLARE #SQL VarChar(1000)
SELECT #SQL ='INSERT INTO #TempTable '+
'SELECT D,Points,#OfferEndDateTime '
exec(#sql)
Please Let me know where I am going wrong
You need to use sp_executesql when passing a parameter to dynamic sql
exec sp_executesql #sql, N'#OfferEndDateTime datetime', #OfferEndDateTime=#OfferEndDateTime
You have, at least, three problems:
The variable needs to be outside:
SELECT #SQL ='INSERT INTO #TempTable '+
'SELECT D,Points,' + #OfferEndDateTime
The variable needs to be varchar type or similar
What is D,Points? They are not defined anywhere. If they are varchar values you nead to quote them (use " or '') for that purpose.
If you need to use the parameter like datetime you should use sp_executesql instead. Check HERE for some info on it!