variables in sp_executesql - sql-server

I have a piece of code:
DECLARE #v int;
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #max_title varchar(30);
SET #IntVariable = 197;
SET #SQLString = N'SELECT #max_titleOUT = max(JobTitle)
FROM some_table
WHERE name = #level';
SET #ParmDefinition = N'#level tinyint, #max_titleOUT varchar(30) OUTPUT';
EXECUTE sp_executesql #SQLString, #ParmDefinition, #level = #v, #max_titleOUT=#max_title OUTPUT;
SELECT #max_title;
I'm a little bit confused about this line:
WHERE name = #level';
If #v is a string instead of an int variable, should I put quotes around #level like this?
WHERE name = ''#level''';
When should I put quotes around a variable inside the #SQLString?

No, #level and #v are variables. You shouldn't put quotes around.
When should I put quotes around a variable inside the #SQLString?
Nowhere

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

How to set the result of a stored procedure to a variable

I am calling a stored procedure like this:
EXEC usp123 #F1 = 1, #F2 = 'A', #F3 = 5
DECLARE #Result int
SET #Result = (EXEC usp123 #F1 = 1, #F2 = 'A', #F3 = 5)
How do I assign a variable to the output of this stored procedure as the above syntax does not work ..
The last line should be
Declare #Result Int
EXEC #Result = usp123 #F1 = 1, #F2 = 'A', #F3 = 5
--Check this... your answer is in the last sentence.
DECLARE #IntVariable int;
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #max_title varchar(30);
SET #IntVariable = 197;
SET #SQLString = N'SELECT #max_titleOUT = max(JobTitle)
FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = #level';
SET #ParmDefinition = N'#level tinyint, #max_titleOUT varchar(30) OUTPUT';
EXECUTE sp_executesql #SQLString, #ParmDefinition, #level = #IntVariable,
#max_titleOUT=#max_title OUTPUT;
SELECT #max_title;

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.

How to call a UDF in master database on a linked server

I am unable to call a UDF in a Linked Server.
Here's my T-SQL code:
DECLARE #Phone_Digits_Input varchar(12);
DECLARE #Phone_Min_Max_Input varchar(5);
DECLARE #Phone_Digits_String varchar(10);
DECLARE #Phone_Min_Max_String varchar(5);
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #phone_digits varchar(10);
SET #Phone_Digits_String = 'phone_digits';
SET #Phone_Min_Max_String = '10-10';
SET #SQLString = N'SELECT #phone_digitsOUT = RemoteServer.master.dbo.myUDF(#Phone_Digits_Input, #Phone_Min_Max_Input)';
SET #ParmDefinition = N'#Phone_Digits_Input varchar(10), #Phone_Min_Max_Input varchar(5), #phone_digitsOUT varchar(10) OUTPUT';
EXECUTE RemoteServer.master.dbo.sp_executesql #SQLString, #ParmDefinition, #Phone_Digits_Input = #Phone_Digits_String,
#Phone_Min_Max_Input = #Phone_Min_Max_String,
#phone_digitsOUT=#phone_digits OUTPUT;
SELECT #phone_digits;
When I run it, I get a message:
Msg 344, Level 16, State 1, Line 1
Remote function reference 'RemoteServer.master.dbo.myUDF' is not allowed, and the column name 'RemoteServer' could not be found or is ambiguous.
How can I fix the issue please?
I got the server name wring! The UDF was i a different database! Sorry for my confusion.
The final code is below:
DECLARE #Phone_Digits_Input varchar(12);
DECLARE #Phone_Min_Max_Input varchar(5);
DECLARE #Phone_Digits_String varchar(10);
DECLARE #Phone_Min_Max_String varchar(5);
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #phone_digits varchar(10);
SET #Phone_Digits_String = 'phone_digits';
SET #Phone_Min_Max_String = '10-10';
SET #SQLString = N'SELECT #phone_digitsOUT = dbo.MyUDF(#Phone_Digits_Input, #Phone_Min_Max_Input)';
SET #ParmDefinition = N'#Phone_Digits_Input varchar(10), #Phone_Min_Max_Input varchar(5), #phone_digitsOUT varchar(10) OUTPUT';
EXECUTE MyServer.MyDB.dbo.sp_executesql #SQLString, #ParmDefinition, #Phone_Digits_Input = #Phone_Digits_String,
#Phone_Min_Max_Input = #Phone_Min_Max_String,
#phone_digitsOUT=#phone_digits OUTPUT;
SELECT #phone_digits;
Thank you.

How to get value for Temp variable in Sql?

I write a query in sql server i am getting value in a temporary variable, this is my query
declare #tacolumn1 varchar(50)='cargo'
declare #temp1 varchar(50)
declare #sql nvarchar(max)
print #tacolumn1
set #sql= ('select '+#tacolumn1+' from operatingincome where YEAR(createddate)= 2009')
exec sp_executesql #sql
print #temp1
from the above #sql has the value , now i want to save that value in #temp1 how can i do that one
sp_executesql procedure can have input and output parameters:
DECLARE #IntVariable int;
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #max_title varchar(30);
SET #IntVariable = 197;
SET #SQLString = N'SELECT #max_titleOUT = max(JobTitle)
FROM AdventureWorks2008R2.HumanResources.Employee
WHERE BusinessEntityID = #level';
SET #ParmDefinition = N'#level tinyint, #max_titleOUT varchar(30) OUTPUT';
EXECUTE sp_executesql #SQLString, #ParmDefinition, #level = #IntVariable, #max_titleOUT=#max_title OUTPUT;
SELECT #max_title;

Resources