EXEC sp executesql con múltiples parámetros


¿Cómo pasar correctamente los parámetros a la instrucción EXEC sp_executesql?

Esto es lo que tengo ahora, pero estoy recibiendo errores:

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 es una lista delimitada por comas de enteros, así: "1,2,3,4,5"

Aquí está mi intento # 2, también sin éxito

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)

Choque de tipo de operando: la fecha es incompatible con int

Author: gotqn, 2015-02-12

2 answers

Aquí hay un ejemplo simple:

EXEC sp_executesql @sql, N'@p1 INT, @p2 INT, @p3 INT', @p1, @p2, @p3;

Su llamada será algo como esto

EXEC sp_executesql @statement, N'@LabID int, @BeginDate date, @EndDate date, @RequestTypeID varchar', @LabID, @BeginDate, @EndDate, @RequestTypeID
 59
Author: SAS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-12 15:37:47

Esto también funciona....a veces es posible que desee construir la definición de los parámetros fuera de la llamada EXEC real.

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
 1
Author: RelativitySQL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-24 16:24:03