EXEC sp_executesql 带多个参数

EXEC sp_executesql with multiple parameters

如何正确的给EXEC sp_executesql语句传递参数?

这是我现在拥有的,但我遇到了错误:

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 是以逗号分隔的整数列表,如下所示:“1,2,3,4,5”

这是我的尝试#2,同样不成功

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

这是一个简单的例子:

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

你的电话会是这样的

EXEC sp_executesql @statement, N'@LabID int, @BeginDate date, @EndDate date, @RequestTypeID varchar', @LabID, @BeginDate, @EndDate, @RequestTypeID

这也有效....有时您可能希望在实际 EXEC 调用之外构造参数的定义。

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

也许这有帮助:

declare 
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'

set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + ''' 
'
exec sp_executesql @statement;

这与下面相同:

select @text1 + ' beautifull ' + @text2

如果需要将 sp_executesqlOUTPUT 变量一起使用:

EXEC sp_executesql @sql
                  ,N'@p0 INT'
                  ,N'@p1 INT OUTPUT'
                  ,N'@p2 VARCHAR(12) OUTPUT' 
                  ,@p0
                  ,@p1 OUTPUT
                  ,@p2 OUTPUT;