EXEC sp_executesql with multiple parameters - sql-server

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

Related

How to store Exec result to datetime variable where exec result has variable table name?

How can I store my execution result in datetime variable?
My query look like this:
Declare #F VARCHAR(50) = (select replace ('H-10','-',''));
DECLARE #SQLQuery AS NVARCHAR(500)
set #SQLQuery=
N'SELECT
top 1 DATEADD(MINUTE, -330, time_stamp) as time
FROM
DMD_'+#F+'_DC_data
ORDER BY
time_stamp ASC';
DECLARE #SOR_time datetime
set #SOR_time=Exec (#SQLQuery)
If you want to store the ... execution result in datetime variable..., one solution is to execute the generated statement using sp_executesql with an OUTPUT parameter:
DECLARE #F varchar(50) = (select replace ('H-10', '-', ''));
DECLARE #SOR_time datetime
DECLARE #SQLQuery AS nvarchar(500)
SET #SQLQuery =
N'SELECT TOP 1 #SOR_time = DATEADD(MINUTE, -330, time_stamp) ' +
N'FROM QUOTE_NAME(DMD_' + #F + '_DC_data) ' +
N'ORDER BY time_stamp ASC'
;
DECLARE #rc int
EXEC #rc = sp_executesql
#SQLQuery,
N'#SOR_time datetime OUTPUT',
#SOR_time OUTPUT
IF #rc <> 0 PRINT 'Error'
Try following way. Execute query result store into the table instead of assign to a variable.
Declare #F VARCHAR(50) = (select replace ('H-10','-',''));
DECLARE #SQLQuery AS NVARCHAR(500)
set #SQLQuery=
N'SELECT
top 1 DATEADD(MINUTE, -330, time_stamp) as time
FROM
DMD_'+#F+'_DC_data
ORDER BY
time_stamp ASC';
DECLARE #TempTable TABLE (SOR_time datetime)
insert #TempTable
exec (#SQLQuery)
select * from #TempTable
You can just assign to variable inside query if result set is just a single variable
Declare #F VARCHAR(50) = (select replace ('H-10','-',''));
DECLARE #SQLQuery AS NVARCHAR(500)
DECLARE #SOR_time DATETIME
set #SQLQuery=
N'SELECT
top 1 #SOR_time = DATEADD(MINUTE, -330, time_stamp)
FROM
DMD_'+#F+'_DC_data
ORDER BY
time_stamp ASC';
-- PRINT #SQLQuery
Exec (#SQLQuery)
SELECT #SOR_time

Openquery with variables in datetime using like clause with linked server

Everytime I execute this query I get this error:
The data types varchar and varchar are incompatible in the modulo operator. Asking for your help. Thanks!
DECLARE #date datetime, #SQL NVARCHAR(MAX);
SET #date = '2019';
SET #SQL = 'SELECT * FROM OPENQUERY(LINK2, ''SELECT * FROM wordpress.wp_users WHERE user_registered LIKE '''%' +#date+ '%''''')';
EXEC sp_executesql #SQL;
you can be varchar(4) because you are setting it as string. then use datepart()
DECLARE #date varchar(4), #SQL NVARCHAR(MAX);
SET #date = '2019';
SET #SQL = 'SELECT * FROM OPENQUERY(LINK2, ''SELECT * FROM wordpress.wp_users WHERE DATEPART(yy, user_registered) LIKE ''''%' +#date+ '%'''''')';
EXEC sp_executesql #SQL;

Must declare the scalar variable "# in tsql

I have a stored procedure as shown below. When i use the command so as to call the stored procedure, i get the error message
Must declare the scalar variable "#MusNo"."
I would like to ask your help.
exec sp_executesql N' execute [isb].[SP_GetNakitIslemSorguList_Test] NULL,159986569,''2016/01/01 12:23:45'',''2016/03/03 21:10:12'' '
USE [ATMDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [isb].[SP_GetNakitIslemSorguList_Test]
(
#IslemKodu as varchar(30),
#MusNo as bigint,
#StartDate as Date,
#EndDate as Date
)
AS
DECLARE #Sql nvarchar(max)
DECLARE #AddToWhereSql varchar(50)
IF #IslemKodu is null
BEGIN
SET #AddToWhereSql = '1=1'
END
ELSE
BEGIN
SET #AddToWhereSql = 'IslemKodu = #IslemKodu'
END
BEGIN
SET #Sql = N'SELECT [KartNo],[HesapNo],[TCKN],[CepTel],[MusNo],[Alacakli],[Tutar],[Tarih],[AtmNo],[Borclu]
FROM [ATMDB].[isb].[NakitIslemSorgu] WITH (NOLOCK)
WHERE MusNo = #MusNo and cast([Tarih] as Date)>= #StartDate and cast([Tarih] as Date) <= #EndDate and CashResult = 0
and ' + #AddToWhereSql + ' ORDER BY Tarih DESC'
exec sp_executesql #Sql
END
GO
As you pass in a Variable #MusNo of type BIGINT you must concatenate its value into your dynamic SQL. Try it like this:
SET #Sql = N'SELECT [KartNo],[HesapNo],[TCKN],[CepTel],[MusNo],[Alacakli],[Tutar],[Tarih],[AtmNo],[Borclu]
FROM [ATMDB].[isb].[NakitIslemSorgu] WITH (NOLOCK)
WHERE MusNo = ' + CAST(#MusNo AS VARCHAR(100)) + ' and cast([Tarih] as Date)>= #StartDate and cast([Tarih] as Date) <= #EndDate and CashResult = 0
and ' + #AddToWhereSql + ' ORDER BY Tarih DESC'
sp_executesql requires the variables to be declared and initialised. This is done using parameters as follows:
DECLARE #Params NVARCHAR(2000);
SET #Params = N'#MusNo bigint, #StartDate Date, #EndDate Date';
exec sp_executesql #Sql, #Params, #MusNo = #MusNo, #StartDate = #StartDate, #EndDate = #EndDate;
Even better is the following which will completely avoid any sql injection.
DECLARE #Sql nvarchar(max)
DECLARE #Params NVARCHAR(2000);
SET #Params = N'#IslemKodu varchar(30), #MusNo bigint, #StartDate Date, #EndDate Date';
SET #Sql = N'SELECT [KartNo],[HesapNo],[TCKN],[CepTel],[MusNo],[Alacakli],[Tutar],[Tarih],[AtmNo],[Borclu]
FROM [ATMDB].[isb].[NakitIslemSorgu] WITH (NOLOCK)
WHERE MusNo = #MusNo and cast([Tarih] as Date)>= #StartDate and cast([Tarih] as Date) <= #EndDate and CashResult = 0
and IslemKodu = ISNULL(#IslemKodu, IslemKodu) ORDER BY Tarih DESC'
exec sp_executesql #Sql, #Params, #IslemKodu = #IslemKodu, #MusNo = #MusNo, #StartDate = #StartDate, #EndDate = #EndDate;

Returning Data from a SQL Server stored procedure

I would like to ask how am I going to return the count(*) because every time I call the stored procedure, it just prints the result.
Here is the code :
ALTER PROCEDURE sp_returnCount
#tblname sysname
, #colname sysname
, #key varchar(10)
AS
DECLARE #sql nvarchar(4000)
DECLARE #num INT
DECLARE #params NVARCHAR (4000)
SELECT #sql = 'SELECT COUNT(*) ' +
' FROM dbo.' + quotename(#tblname) +
' WHERE ' + quotename(#colname) + ' LIKE #key'
EXEC sp_executesql #sql, N'#key varchar(10)', #key
--just prints 5 or any numbers...
I'd like to return the count(*) to use it in another query. Thanks in advance.
ALTER PROCEDURE sp_returnCount
#tblname sysname
, #colname sysname
, #key varchar(10)
AS
DECLARE #sql nvarchar(4000)
DECLARE #num INT
DECLARE #params NVARCHAR (4000)
DECLARE #count int
SELECT #sql = 'SELECT #count = COUNT(*) ' +
' FROM dbo.' + quotename(#tblname) +
' WHERE ' + quotename(#colname) + ' LIKE #key'
EXEC sp_executesql #sql, N'#key varchar(10), #count int OUTPUT', #key, #count OUTPUT

How to set value to variable using 'execute' in t-sql?

DECLARE #dbName nvarchar(128) = 'myDb'
DECLARE #siteId int
exec ('SELECT TOP 1 #siteId = Id FROM ' + #dbName + '..myTbl')
select #siteId
When I run the script above I get the following error
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "#siteId".
(1 row(s) affected)
Why and how to fix it?
Thank you
You can use output parameters with sp_executesql.
DECLARE #dbName nvarchar(128) = 'myDb'
DECLARE #siteId int
DECLARE #SQL nvarchar(max) = N'SELECT TOP 1 #outputFromExec = Id FROM ' + quotename(#dbName) + N'..myTbl'
exec sp_executesql #SQL, N'#outputFromExec int out', #siteId out
select #siteId
The dynamic SQL is a different scope to the outer, calling SQL: so #siteid is not recognised
You'll have to use a temp table/table variable outside of the dynamic SQL:
DECLARE #dbName nvarchar(128) = 'myDb'
DECLARE #siteId TABLE (siteid int)
INSERT #siteId
exec ('SELECT TOP 1 Id FROM ' + #dbName + '..myTbl')
select * FROM #siteId
Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY
You can try like below
DECLARE #sqlCommand NVARCHAR(4000)
DECLARE #ID INT
DECLARE #Name NVARCHAR(100)
SET #ID = 4
SET #sqlCommand = 'SELECT #Name = [Name]
FROM [AdventureWorks2014].[HumanResources].[Department]
WHERE DepartmentID = #ID'
EXEC sp_executesql #sqlCommand, N'#ID INT, #Name NVARCHAR(100) OUTPUT',
#ID = #ID, #Name = #Name OUTPUT
SELECT #Name ReturnedName
Source : blog.sqlauthority.com
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Andrew Foster
-- Create date: 28 Mar 2013
-- Description: Allows the dynamic pull of any column value up to 255 chars from regUsers table
-- =============================================
ALTER PROCEDURE dbo.PullTableColumn
(
#columnName varchar(255),
#id int
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #columnVal TABLE (columnVal nvarchar(255));
DECLARE #sql nvarchar(max);
SET #sql = 'SELECT ' + #columnName + ' FROM regUsers WHERE id=' + CAST(#id AS varchar(10));
INSERT #columnVal EXEC sp_executesql #sql;
SELECT * FROM #columnVal;
END
GO
A slight change in the execute query will solve the problem:
DECLARE #dbName nvarchar(128) = 'myDb'
DECLARE #siteId int
exec ('SELECT TOP 1 **''#siteId''** = Id FROM ' + #dbName + '..myTbl')
select #siteId

Resources