How do you use OPENQUERY within sp_executesql? - sql-server

I'm trying to verify a job number exists on a linked server and get back a variable (#JobExists) indicating whether it does or not (1 for yes, 0 for no).
To do this I'm trying to use OPENQUERY along with sp_executesql as I have to pass in a parameter for the job number. I've tried the code below but get the error 'Procedure expects parameter '#statement' of type 'ntext/nchar/nvarchar'. For testing purposes I've declared and set the variable #JobNumber.
DECLARE #JobNumber as varchar(50)
SET #JobNumber = '2112111'
DECLARE #JobExists as BIT
DECLARE #JobCount as int
DECLARE #ParmDefinition as varchar(100)
DECLARE #sql as varchar(500)
SET #JobExists = 0
SET #ParmDefinition = N'#Result int output'
SET #sql = 'SELECT #Result = SELECT COUNT(*) FROM OPENQUERY(MYLINKEDSVR,''SELECT JOB_NUMBER FROM PROD.tbl1 WHERE JOB_NUMBER = ''''' + UPPER(RTRIM(LTRIM(#JobNumber))) + ''''''')'
exec sp_executesql #sql, #ParmDefinition, #Result = #JobCount output
IF #JobCount > 0
SET #JobExists = 1
SELECT #JobExists
I've read up sp_executesql here: http://technet.microsoft.com/en-us/library/ms188001.aspx
I've also done various searches but haven't come across any answers that work for me.
Is there something I'm missing?

The error message is clear: you must declare #sql as nvarchar and not as varchar.
The same for #ParamDefinition:
DECLARE #ParmDefinition as nvarchar(100)
DECLARE #sql as nvarchar(500)

Related

Execute SQL with "SELECT #daynamic_variable_name" in SQL SERVER

Through the exec in SQL Server, I want to retrieve the parameter's value dynamically. Please look into the below Example:
declare #p1 varchar(50) = '10'
declare #p2 varchar(50) = '20'
declare #p_nm varchar(50)
set #p_nm = '#p1' -- OR set #p_nm = '#p2'
declare #sql varchar(50) = 'select #p1'
declare #ans_val varchar(50)
set #ans_val = exec #sql
How could I get the result 10 if using set #p_nm = '#p1' and 20 if using set #p_nm = '#p2'?
In my case set #ans_val = exec #sql giving syntax error.
A variable only has scope within the batch it is inside. When you run dynamic SQL, the dynamic SQL has a different scope, so variables cannot be accessed if they are in a different one. For example, both of the following statements will generate an error:
DECLARE #SQL nvarchar(MAX) = N'SELECT #i;';
DECLARE #i int = 1;
EXEC (#SQL);
GO
DECLARE #SQL nvarchar(MAX) = N'DECLARE #i int = 1;';
EXEC (#SQL);
SELECT #i;
GO
If you are running dynamic SQL, you need to pass details of any variables as parameters, using sp_executesql. For example:
DECLARE #SQL nvarchar(MAX) = N'SELECT #n;';
DECLARE #i int = 1;
EXEC sp_executesql #SQL, N'#n int', #n = #i;
If you want the return scalar values to a variable, use an OUTPUT parameter (personally, I recommend against the syntax {Variable} = EXEC {Expression/Stored Procedure}, one reason being you are therefore limited to one scalar value).
So, again, as an example:
DECLARE #SQL nvarchar(MAX) = N'SET #a = #n + 1;';
DECLARE #i int = 1, #b int;
EXEC sp_executesql #SQL, N'#n int, #a int OUTPUT', #n = #i, #a = #b OUTPUT;
PRINT #b;
I'll do it like:
EXECUTE sp_executesql
N'SELECT #Var AS Result',
N'#Var VARCHAR(5)',
#Var = '12345';
Results:
+----+--------+
| | Result |
+----+--------+
| 1 | 12345 |
+----+--------+
Or
DECLARE #Out VARCHAR(5);
EXECUTE sp_executesql
N'SELECT #Out = #Var',
N'#Var VARCHAR(5) , #Out VARCHAR(5) OUTPUT',
#Var = '12345',
#Out = #Out OUTPUT;
SELECT #Out As Result;
Finally, please don't forgot to visit sp_executesql

Must Declare Scalar variable #nRuleId

USE GDMDBNS_1720
GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE = 'PROCEDURE'
AND ROUTINE_SCHEMA = 'dbo' AND ROUTINE_NAME = 'usp_RmsExecuteValidationRule')
BEGIN
DROP PROCEDURE dbo.usp_RmsExecuteValidationRule
END
GO
Create PROCEDURE [dbo].[usp_RmsExecuteValidationRule]
#nRuleId INT,
#FIPSName VARCHAR(5)
AS
BEGIN
DECLARE #strRuleQuery VARCHAR(MAX)
DECLARE #sqlstat AS NVARCHAR(MAX)
DECLARE #params AS NVARCHAR(MAX)
SET #strRuleQuery = N'SELECT RULE_QUERY from GdmValidationRuleMaster where
RULE_ID = #nRuleId'
SET #sqlstat = #strRuleQuery
SET #params = N'#FIPSName VARCHAR(5)'
EXEC sp_executesql #params,
#query = #sqlstat,
#FIPSName = #FIPSName
END
got error while Debugging must declare scalar variable #nRuleId . I have already declared. But error is pooping out always.
There appear to be a number of issues with the code, as is.
To return a value, you need to declare an OUTPUT parameter and the variable #FIPSName is not actually used in the code, and #strRuleQuery is superfluous in this code.
Here is the code from inside the SProc, that should be closer to your needs.
-- Parameters
DECLARE
#nRuleId INT = 1,
#FIPSName VARCHAR(5) = 'ITS'
-- Local variables
DECLARE #sqlstat AS NVARCHAR(MAX)
DECLARE #params AS NVARCHAR(MAX)
DECLARE #RULE_QUERY NVARCHAR(MAX)
SET #sqlstat = N'SELECT #RULE_QUERY=RULE_QUERY from GdmValidationRuleMaster where RULE_ID = #nRuleId'
SET #params = N'#nRuleId INT, #RULE_QUERY NVARCHAR(MAX) OUTPUT'
EXEC sp_executesql
#sqlstat,
#params,
#nRuleId = #nRuleId, #RULE_QUERY= #RULE_QUERY OUTPUT
-- Output
SELECT #RULE_QUERY
You must rewrite execution part:
SET #params = N'#FIPSName VARCHAR(5), #nRuleId int'
EXEC sp_executesql #strRuleQuery, #params, #FIPSName = #FIPSName, #nRuleId = #nRuleId
I don't understand, why do you pass #FIPSName as parameter, it is not used in your batch.

using parameters in group by statment

I just wanna do a simple query with grouping by "Age_Band".
And to set the parameter to help me change the grouping column easily.
But got an error:
"Each GROUP BY expression must contain at least one column that is not an outer reference. "
How did I make mistake on using the parameter? Thanks a lot
DECLARE #group nvarchar(50);
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
SET #SQLString =
N'SELECT AVG(Loan_Amount) as Avg_Loan_Amount
,count(Loan_Amount)
,SUM(Loan_Amount) as Sum_Loan_Amount
,SQRT(SUM(Loan_Amount)) as Square_Loan_Amount
,Age_Band
,SUM(Interest_Paid_Amount) as Sum_Interest_Paid_Amount
,GETDATE()as today
FROM [dbo].[Loan]
group by #groupcol';
SET #ParmDefinition = N'#groupcol nvarchar(50)';
SET #group=N'Age_Band'
exec sp_executesql #SQLString, #ParmDefinition,
#groupcol = #group;
You cannot use parameter in the group by clause by you can build query string using parameter. Something like this.
DECLARE #group nvarchar(50) = N'Age_Band'; --set col name
DECLARE #SQLString nvarchar(500);
SET #SQLString =
N'SELECT AVG(Loan_Amount) as Avg_Loan_Amount
,count(Loan_Amount)
,SUM(Loan_Amount) as Sum_Loan_Amount
,SQRT(SUM(Loan_Amount)) as Square_Loan_Amount
,' + #group + '
,SUM(Interest_Paid_Amount) as Sum_Interest_Paid_Amount
,GETDATE()as today
FROM [dbo].[Loan]
group by ' + #group;
exec sp_executesql #SQLString;

Can I specify a database name dynamically in a trigger?

I need to get data from a table in a database who's database name will be determined as a variable during a trigger. I then, knowing this variable need to get a seqno from a table in the determined database for a item which was also determined as a variable during a trigger.
I am trying this route as I assume I need to build the SQL statement before I set it to a variable.
This is not working and I need to know the best way on how I can do this:
DECLARE #SU_SEQNO INTEGER, #SU_NAME VARCHAR(50), #SU_OWNER VARCHAR(15), #SUD_SEQNO INTEGER, #SQL NVARCHAR(500)
SET #SU_OWNER = 'XXX'
SET #SU_NAME = '1ABC234'
SET #SQL ='SELECT #SUD_SEQNO=SEQNO FROM ' + (#SU_OWNER) + '.SU_MAIN
WHERE UNITNAME= ' + #SU_NAME
SET #SUD_SEQNO = (EXECUTE (#SQL))
Thanks alot for any help with this
From: Get result from dynamic SQL in stored procedure
SET #SQL = N'SELECT DISTINCT #FiscalYear = FiscalYear FROM ' + #DataSource;
EXEC sp_executesql #SQL, N'#FiscalYear INT OUTPUT', #FiscalYear OUTPUT;
PRINT #FiscalYear;
I'd re-engineer to use the sp_executesql method as shown above. That should do the trick.
I have amended the code, and it works
declare #su_owner varchar(15) = 'DBTEST'
declare #SU_SEQNO INTEGER=1, #SUD_SEQNO INTEGER=0, #SQL NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500), #SU_NAME_INPUT VARCHAR(50)='SU123'
SET #SU_NAME_INPUT = (SELECT UNITNAME FROM SU_MAIN WHERE SEQNO=#SU_SEQNO)
SET #SU_NAME = (SELECT UNITNAME FROM SU_MAIN WHERE SEQNO=#SU_SEQNO)
SET #SQL = N'SELECT #sud_seqnoOUT=MAX(SEQNO) FROM ' + quotename(#su_owner) + '.[dbo].[SU_MAIN] WHERE UNITNAME]=#SU_NAME_INPUT' ;
SET #ParmDefinition = N'#SU_NAME_INPUT VARCHAR(50),#sud_seqnoOUT INT OUTPUT'
EXEC sp_executesql #SQL,#ParmDefinition,#SU_NAME_INPUT = #SU_NAME,
#sud_seqnoOUT = #SUD_SEQNO OUTPUT

passing a TSQL function database name

Is there any way to pass a tsql function a database name so it can perform selects on that database
ALTER function [dbo].[getemailjcp]
(
#DB_Name varchar(100)
)
Returns varchar(4000)
AS
BEGIN
DECLARE #out varchar (4000);
DECLARE #in varchar (1000);
Set #out =
(select substring
((select ';' + e.email from
(SELECT DISTINCT ISNULL(U.nvarchar4, 'NA') as email
FROM [#DB_Name].dbo.Lists ...
In order to create dynamic SQL statement you should store procedure. For example:
DECLARE #DynamicSQLStatement NVARCHAR(MAX)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #FirstID BIGINT
SET #ParmDefinition = N'#FirstID BIGINT OUTPUT'
SET #DynamicSQLStatement=N' SELECT #FirstID=MAX(ID) FROM ['+#DatabaseName+'].[dbo].[SourceTable]'
EXECUTE sp_executesql #DynamicSQLStatement,#ParmDefinition,#FirstID=#FirstID OUTPUT
SELECT #FirstID
In this example:
#DatabaseName is the passed as parameter to your procedure.
#FirstID is output parameter - this value might be return from your procedure.
Here you can find more information about "sp_executesql":
http://msdn.microsoft.com/en-us/library/ms188001.aspx
a better solution might be to replace "#DatabaseName" (a char variable)with:
"DB_NAME(<#DBId>)".
You can then continue to pass in the db names, but 1st converting them to IDs in the fcn. Also kinda resolves the contradiction of building a SQL stmt w/ a char variable in it, if using "sp_executesql" to help guard against SQL injection ("DB_NAME()" isn't a variable/can't be substituted).
So you'd have this:
DECLARE #DynamicSQLStatement NVARCHAR(MAX)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #FirstID BIGINT
DECLARE #DBId INT
SET #DBId = DB_ID(#Db_Name) --raise the proper security/robustness** concern if this doesn't resolve.
SET #ParmDefinition = N'#FirstID BIGINT OUTPUT'
SET #DynamicSQLStatement=N' SELECT #FirstID=MAX(ID) FROM ['+DB_NAME(#DBId)+'].[dbo].[SourceTable]'

Resources