Handling nvarchar parameter vs decimal - sql-server

This works:
declare #sql nvarchar(4000)
declare #minAmount decimal
set #sql = N'select PRODUCTGROUP
from dbo.ICMaster
where ONHAND > #minAmount'
set #minAmount = 400
print #sql
exec sp_executesql #sql, N'#minAmount decimal', #minAmount
But as soon as I change the #minAmount to nvarchar, it does not (no errors but the output is null). What am I missing ?
declare #sql nvarchar(4000)
declare #minAmount nvarchar(100)
set #sql = N'select PRODUCTGROUP
from dbo.ICMaster
where PRODUCTGROUP = #minAmount'
set #minAmount = '400'
print #sql
exec sp_executesql #sql, N'#minAmount nvarchar', #minAmount
I also tried :
set #minAmount = char(39)+'400'+char(39)

The value you query PRODUCTGROUP for is 4 not 400 because you forgot a size for the nvarchar:
exec sp_executesql #sql, N'#minAmount nvarchar(4000)', #minAmount

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

save result of exec sp_excutequery using xpath

Hi i have this example
DECLARE
#XML1 xml,
#XPath nvarchar(200),
#EncodedXPath nvarchar(200),
#Sql nvarchar(max),
#val nvarchar(20)
SET #XML1='
<Root>
<Device>
<Inspection>
<Status>OK</Status>
</Inspection>
</Device>
</Root>'
SELECT #XML1.query('/Root[1]/Device[1]/Inspection[1]/Status[1]')
SELECT #XML1.value('/Root[1]/Device[1]/Inspection[1]/Status[1]','varchar(5)')
SET #XPath = '/Root[1]/Device[1]/Inspection[1]/Status[1]'
SET #EncodedXPath = REPLACE(#XPath, '''', '''''')
SET #Sql = N'SELECT #XML1.query(''' + #EncodedXPath + N''')'
EXEC sp_executesql #Sql, N'#XML1 xml', #XML1
SET #Sql = N'SELECT #XML1.value(''' + #EncodedXPath + N''', ''varchar(5)'')'
EXEC sp_executesql #Sql, N'#XML1 xml', #XML1
if you execute the code above you get same result, but how can i assign the result of the dynamic sql to a variable using xpath? the below example return just the result of the execution but i want to get back the value 'OK'
EXEC #ret = sp_executesql #Sql, N'#XML1 xml', #XML1
The approach should be the same as getting result of any sp_executesql into a variable, no matter the sp_executesql contains XPath or just plain SQL.
This is one possible way, which also suggested in "How to get sp_executesql result into a variable?". Modify your dynamic SQL to have an output variable for storing the result of the XPath query. Then you can set your static variable -the one declared outside sp_executesql- from the output variable value :
....
SET #Sql = N'SET #ret = #XML1.value(''' + #EncodedXPath + N''', ''varchar(5)'')'
EXEC sp_executesql #Sql, N'#XML1 xml, #ret varchar(5) output', #XML1, #ret = #ret output

how to assign results from exec to variable

How do I assign the results of an exec command to a variable. like the below, so when I do select #sql2 I get the result of the executed varchar sql.
declare #sql varchar(500)
declare #sql2 varchar(max)
set #sql = 'SELECT
PDB.OutletBrandID, OB.BrandName
FROM
ProductDistributionBrand PDB
INNER JOIN
[IND_roadchef].dbo.OutletBrands OB
ON
PDB.OutletBrandID = OB.OutletBrandID
FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE'
--select #sql
set #sql2 = exec(#sql)
select #sql2
Use an output param:
declare #sql nvarchar(500)
declare #xml XML
set #sql = 'set #xml = (SELECT ..... FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE)'
EXEC sp_executesql #sql, N'#xml XML output', #xml = #xml OUTPUT
select #xml
You can use Table Variables. Try like this,
DECLARE #sql TABLE (col1 VARCHAR(500))
DECLARE #sql2 VARCHAR(max)
SET #sql2 = 'SELECT
PDB.OutletBrandID, OB.BrandName
FROM
ProductDistributionBrand PDB
INNER JOIN
[IND_roadchef].dbo.OutletBrands OB
ON
PDB.OutletBrandID = OB.OutletBrandID
FOR XML PATH(''ProductDistributionBrandDetail''),ROOT(''ProductDistributionBrandDetails''),TYPE'
INSERT INTO #sql
EXEC (#sql2)
SELECT *
FROM #sql
Please see reference from this link it will show you how to use output parameters
https://support.microsoft.com/en-us/kb/262499

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

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