EXEC sp_executesql with multiple parameters

后端 未结 4 782
逝去的感伤
逝去的感伤 2020-11-27 06:12

How to pass the parameters to the EXEC sp_executesql statement correctly?

This is what I have now, but i\'m getting errors:

alter PROCE         


        
相关标签:
4条回答
  • 2020-11-27 06:30

    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
    
    0 讨论(0)
  • 2020-11-27 06:32

    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;
    
    0 讨论(0)
  • 2020-11-27 06:36

    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
    
    0 讨论(0)
  • 2020-11-27 06:36

    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
    
    0 讨论(0)
提交回复
热议问题