How to get value for Temp variable in Sql? - sql-server

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;

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

variables in sp_executesql

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

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.

EXEC sp_executesql with multiple parameters

How to pass the parameters to the EXEC sp_executesql statement correctly?
This is what I have now, but i'm getting errors:
alter PROCEDURE [dbo].[usp_getReceivedCases]
-- Add the parameters for the stored procedure here
#LabID int,
#RequestTypeID varchar(max),
#BeginDate date,
#EndDate date
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #statement nvarchar(4000)
set #statement = N'select SentToLab,
FROM dbo.vEmailSent
WHERE SentToLab_ID=#LabID and convert(date,DateSent) >= #BeginDate
and CONVERT(date, datesent) <= #EndDate
and RequestType_ID in ( #RequestTypeID )
EXEC sp_executesql #statement,N'#LabID int', #LabID, N'#BeginDate date', #BeginDate,N'#EndDate date', #EndDate, #RequestTypeID=#RequestTypeID
END
RequestTypeID is a comma delimited list of integers, like so: "1,2,3,4,5"
here is my try #2, also unsuccessful
declare #statement nvarchar(4000)
SET #statement =' select SentToLab_ID
FROM dbo.vEmailSent
WHERE
SentToLab_ID='+#LabID+' and convert(date,DateSent) >= '+#BeginDate +'
and CONVERT(date, datesent) <= '+#EndDate+'
and RequestType_ID in ('+ #RequestTypeID+' )
group by FileStream_ID, SentToLab_ID'
EXEC(#statement)
Operand type clash: date is incompatible with int
Here is a simple example:
EXEC sp_executesql #sql, N'#p1 INT, #p2 INT, #p3 INT', #p1, #p2, #p3;
Your call will be something like this
EXEC sp_executesql #statement, N'#LabID int, #BeginDate date, #EndDate date, #RequestTypeID varchar', #LabID, #BeginDate, #EndDate, #RequestTypeID
This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.
DECLARE #Parmdef nvarchar (500)
DECLARE #SQL nvarchar (max)
DECLARE #xTxt1 nvarchar (100) = 'test1'
DECLARE #xTxt2 nvarchar (500) = 'test2'
SET #parmdef = '#text1 nvarchar (100), #text2 nvarchar (500)'
SET #SQL = 'PRINT #text1 + '' '' + #text2'
EXEC sp_executeSQL #SQL, #Parmdef, #xTxt1, #xTxt2
If one need to use the sp_executesql with OUTPUT variables:
EXEC sp_executesql #sql
,N'#p0 INT'
,N'#p1 INT OUTPUT'
,N'#p2 VARCHAR(12) OUTPUT'
,#p0
,#p1 OUTPUT
,#p2 OUTPUT;
maybe this help :
declare
#statement AS NVARCHAR(MAX)
,#text1 varchar(50)='hello'
,#text2 varchar(50)='world'
set #statement = '
select '''+#text1+''' + '' beautifull '' + ''' + #text2 + '''
'
exec sp_executesql #statement;
this is same as below :
select #text1 + ' beautifull ' + #text2

Resources