EXEC sp_executesql a parameter is not passed - sql-server

I need your help please,
I read the forum but I'm still having a persistant problem without solution. I want to pass a variable into parameters of an SP_EXECUTESQL, but the result value of the passed variable is always ZERO in my SQL statement.
Here is my code :
declare #counter int
declare #sql nvarchar(max)
// ------ My #COUNTER value I want to get, it's ok
SET #counter = (
select COUNT(CREATED_DT)
from USERS
where CAST(CREATED_DT as date) = CAST(#DATE_TIME as date)
)
// ------ I try to pass my #COUNTER value for my COUNTER_COLUMN, and it's not ok anymore...
SET #sql = N'update DATA_REPORT set COUNTER_COLUMN = #counterB';
EXEC sp_executesql #sql, N'#counterB int', #counterB = #counter;
I do not have errors on execution but in my SQL there is always :
COUNTER_COLUMN = 0 !!! I checked before that my #counter was not returning 0, and it returns perfectly miscenaneous good values.
Any clues about this issue ?
Thank you very much :)
Robin

Have you tried this:
declare #sql nvarchar(max)
SET #sql = N'update myTable set avg = (
select COUNT(CREATED_DT)
from USERS
where CAST(CREATED_DT as date) = CAST(#DATE_TIME as date)
)';
EXEC sp_executesql #sql

Greatly simplifying this to remove the unnecessary dynamic sql it would like something like this.
update DATA_REPORT
set COUNTER_COLUMN =
(
select COUNT(CREATED_DT)
from USERS
where CAST(CREATED_DT as date) = CAST(#DATE_TIME as date)
)

From your query, i try to use 'concat' the parameter instead of using #counterB and it work just fine.
declare #sql nvarchar(max)
declare #counter int = 1
set #sql = concat(N'update DATA_REPORT set COUNTER_COLUMN = ', #counter);
exec sp_executesql #sql
#sql look like this
update DATA_REPORT set COUNTER_COLUMN = 1

Thanks to all of you,
Your answers were very interesting and helped me to think differently and to solve my issue. I choosed to execute my statement the more simple as possible without #parameters with sp_executesql. It made problems with the TYPE of my variables.
PS. #Rawitas Krungkaew > I didn't try CONCAT but keep it in mind, thk you.
declare #dyn_col_account varchar(40);
declare #DATE_TIME nvarchar(50)
SET #counter = (
select COUNT(CREATED_DT)
from USERS
where CAST(CREATED_DT as date) = CAST(#DATE_TIME as date)
)
DECLARE #query1 nvarchar(max) = '
UPDATE DATA_REPORT
SET ['+#dyn_col_account+'] = '+ #counter +'
WHERE TIME_DAY=cast('''+#DATE_TIME+''' as date)'
EXECUTE sp_executesql #query1

Related

Passing Variable Into OpenQUERY SQL Server 2016

EDIT: SQL Server Version
I'm trying to pass this variable into my open query using this guide from Microsoft: Link
I'm running into this error message "Statement(s) could not be prepared." Which I believe means something is wrong with the OpenQuery. I'm just not sure what is wrong.
Here's the code:
DECLARE #ticketid INT, #QLFD VARCHAR(8000)
SELECT #ticketid = '296272348'
SELECT #QLFD = 'SELECT
*
FROM
OPENQUERY(
[Server_name],''
SELECT
ticket_id
, QLFD_SPD_AMT
FROM [database].[dbo].[table]
WHERE ticket_id = #ticketid
'')'
EXEC (#QLFD)
Could you help me identify the error? I prefer to do it passing the whole query as one.
Thanks!
Edit:
After looking at suggestions made by #Larnu. I have adjusted my code to:
DECLARE #ticketid INT--, #QLFD NVARCHAR(Max)
SELECT #ticketid = '296272348'
DECLARE #QLFD NVARCHAR(Max) = 'SELECT
*
FROM
OPENQUERY(
[Server_name],''
SELECT
ticket_id
, QLFD_SPD_AMT
FROM [database].[dbo].[table]
WHERE ticket_id = QUOTENAME(#ticketid, '''''''')
'')';
EXEC (#QLFD);
As I mentioned, you can't parametrise a query with OPENQUERY you have safely inject the values.
Normally that would be with QUOTENAME or REPLACE, but you don't actually need to do that here, due to the value being a numerical data type, so you can just concatenate it in:
DECLARE #ticketid int = 296272348; --Don't wrap numerical datatypes with quotes.
DECLARE #SQL nvarchar(MAX),
#OpenQuery nvarchar(4000);
SET #OpenQuery = CONCAT(N'SELECT QLFD_SPD_AMT
FROM [database].[dbo].[table]
WHERE ticket_id = ',#ticketid,N';'); --As it's an int we dont need to quote
SET #SQL = CONCAT(N'SELECT #ticketid AS ticket_id, QLFD_SPD_AMT
FROM OPENQUERY([servername],N''',REPLACE(#OpenQuery,'''',''''''),N''');';
EXEC sys.sp_executesql #SQL, N'#ticketid int', #ticketid;

Getting Empty Output

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);

Use sql variable as where clause in sql

i want to do this:
DECLARE #str varchar(max)
DECLARE #cnt bigint
set #str= 'where column=value'
set #cnt= (select count(*) from user+#str)
but the where clause is not working. getting no error but it will just ignore the where condition.
I previously suggested wrapping your last line in EXEC(), but you can't do this and return results to a variable. To do that, use the following in place of your last line:
create table #temp (theCount int)
insert into #temp EXEC('select count(*) from Photos '+#str)
set #cnt= (select top 1 theCount from #temp)
drop table #temp
Check below code, in your case condition is dynamic so you need to dynamic sql.
DECLARE #sSQL nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #str nvarchar(500);
set #str= 'where column=value'
SELECT #sSQL = N'SELECT #retvalOUT = COUNT(*) FROM user '+ #str +' ' ;
SET #ParmDefinition = N'#retvalOUT int OUTPUT';
EXEC sp_executesql #sSQL, #ParmDefinition, #retvalOUT=#retval OUTPUT;
SELECT #retval;
use the execute sql syntax http://technet.microsoft.com/en-us/library/ms188001.aspx
Hope this will solve your problem

How do you use OPENQUERY within sp_executesql?

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)

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

Resources