Iam trying to Execute Dynamic Query, But Iam getting Empty Output.Where I'm Wrong?
SET #SQL=N'
SELECT GETDATE(),'+#AMUID+','+ #BNO +
',LOT,BARCODEID,'+#ACTWT+',TARE_QUANTITY,''NA'',STAGE,0,0,0,
'+ #UNAME+ ','+#PR + ',GETDATE()
FROM DISPENSE_HOLD_START WHERE BATCH_NO='''+#BNO+''' AND BARCODEID='''+
#BARID +''' and IS_OUT=0';
PRINT(#SQL)
Here #AMUID,#BNO,#ACTWT etc are Input Parameters Declared with NVARCHAR(MAX) data type.They are dynamic Iam getting nothing When I Print this.
as you are not executing the query but printing it
this is same as
3+3=6 and "3"+"3"="33"
the dynamic queries are typically executed like this(simplest method)
DECLARE #IntVariable int;
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
/* Build the SQL string one time.*/
SET #SQLString =
N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
FROM AdventureWorks2012.HumanResources.Employee
WHERE BusinessEntityID = #BusinessEntityID';
SET #ParmDefinition = N'#BusinessEntityID tinyint';
/* Execute the string with the first parameter value. */
SET #IntVariable = 197;
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#BusinessEntityID = #IntVariable;
/* Execute the same string with the second parameter value. */
SET #IntVariable = 109;
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#BusinessEntityID = #IntVariable;
Case#1 :
In your Above Query, You are using PRINT instead of EXEC. So Make sure you are executing the Query in your actual Code
EXEC(#SQL)
Case#2 :
If you are executing this, there is a possibility that if any of the Parameter Value is NULL, then the entire String will become NULL
If you add any Value to NULL the Result will be NULL
SELECT
'ABC',
'ABC'+NULL
Gives Me this
So Use ISNULL
SET #SQL = N'
SELECT
GETDATE(),
'+ISNULL(#AMUID,'')+','+ISNULL(#BNO,'')+',LOT,
BARCODEID,'+ISNULL(#ACTWT,'')+',TARE_QUANTITY,''NA'',STAGE,0,0,0,
'+ISNULL(#UNAME,'')+','+ISNULL(#PR,'')+',GETDATE()
FROM DISPENSE_HOLD_START
WHERE BATCH_NO='''+ISNULL(#BNO,'')+'''
AND BARCODEID='''+ISNULL(#BARID,'')+'''
and IS_OUT=0';
EXEC(#SQL);
Case#3
Looking at your Code, I think you don't need a Dynamic SQL here. Instead, you can directly go Like this
SELECT
GETDATE(),
#AMUID,
#BNO,
LOT,
BARCODEID,
#ACTWT,
TARE_QUANTITY,
'NA',
STAGE,
0,
0,
0,
#UNAME,
#PR,
GETDATE()
FROM DISPENSE_HOLD_START
WHERE BATCH_NO = #BNO
AND BARCODEID = #BARID
AND IS_OUT = 0
Works just fine for me
declare #val nvarchar(100) = 'tommy can you see me'
declare #SQL nvarchar(100) = N'SELECT GETDATE(), ''' + #val + '''';
PRINT(#SQL);
Related
My requirement is to retrieve into a variable, the next value for a sequence, the name of which is derived from a string and a value.
When I run the following as a test using exec sp_executesql ... an error is reported:
Incorrect syntax near #sequenceName
What's wrong with my code?
DECLARE #nextSeqID varchar(10);
DECLARE #sql nvarchar(100);
DECLARE #eqtypeID int;
DECLARE #sequence nvarchar(50);
DECLARE #paramdef nvarchar(100);
SET #eqtypeID = 7;
SET #sequence = 'dbo.seq_eqtype_autoserno_' + CAST(#eqtypeID as nvarchar(8));
-- #sequence = dbo.seq_eqtype_autoserno_7
SET #sql = N'SELECT #nextSeqID_OUT = NEXT VALUE FOR #sequenceName';
-- #sql = SELECT #nextSeqID_OUT = NEXT VALUE FOR #sequenceName
SET #paramdef = N'#nextSeqID_OUT varchar(10) OUTPUT, #sequenceName nvarchar(50)';
-- #paramdef = #nextSeqID_OUT varchar(10) OUTPUT, #sequenceName nvarchar(50)
EXEC sp_executesql #sql, #paramdef, #sequenceName = #sequence, #nextSeqID_OUT = #nextSeqID OUTPUT;
/*
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '#sequenceName'.
*/
It is admirable and correct that you are using sp_executesql to pass dynamic things through variables. However, you can not do this with object names(like a sequence) and other stuff which are required by the query at runtime.
Remove #sequenceName from the parameters and the definition, and put it directly on the code. The correct way to do this to still be safe from injection is to use it within quotename, so whatever injection attack happens, it will be quoted, and thus safe:
SET #sql = N'SELECT #nextSeqID_OUT = NEXT VALUE FOR '+quotename(#sequenceName);
SET #paramdef = N'#nextSeqID_OUT varchar(10) OUTPUT';
EXEC sp_executesql #sql, #paramdef, #nextSeqID_OUT = #nextSeqID OUTPUT;
I have a query like this:
DECLARE #TaskId UNIQUEIDENTIFIER
DECLARE #TaskName VARCHAR(255) = 'MasterSet'
DECLARE #sql NVARCHAR(MAX)
DECLARE #StartingDateTask DATETIME2 = (SELECT TOP 1 [Date]
FROM [TaskStatusAudit]
WHERE [TaskId] = 'A1FDFC16-904D-4560-B19D-5E7D4FEB1C2B'
AND [TaskStatusName] = 'IN-PROGRESS')
DECLARE #EndingDateTask DATETIME2 = (SELECT TOP 1 [Date]
FROM [TaskStatusAudit]
WHERE [TaskId] = 'A1FDFC16-904D-4560-B19D-5E7D4FEB1C2B'
AND [TaskStatusName] = 'COMPLETED')
SET #sql = N'SELECT dbo.TotalMinuteRange(#StartingDateTask,#EndingDateTask) as ' + quotename(#TaskName) + N''
EXEC sp_executesql #sql
Problem is when I execute it I get this error:
Must declare the scalar variable "#StartingDateTask".
Any ideas why I getting that if I declare my variable correctly? Regards
When executing sp_executesql you need to declare and pass the variables to sp_executesql something like..
SET #sql = N'SELECT dbo.TotalMinuteRange(#StartingDateTask,#EndingDateTask) as '
+ quotename(#TaskName) + N''
exec sp_executesql #sql
, N'#StartingDateTask DATETIME2 , #EndingDateTask DATETIME2'
, #StartingDateTask
, #EndingDateTask
Second parameter is the variable declaration parameter followed by the actual variables separately.
You can also do like taking a parameters variable and assign it.
declare #params nvarchar(100)
set #params='#StartingDateTask DATETIME2,#EndingDateTask DATETIME2'
SET #sql = N'SELECT dbo.TotalMinuteRange(#StartingDateTask,#EndingDateTask) as '
+ quotename(#TaskName) + N''
exec sp_executesql #sql
, #params
, #StartingDateTask
, #EndingDateTask
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;
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)
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