How to get sp_executesql result into a variable?

后端 未结 10 1502
刺人心
刺人心 2020-11-22 16:06

I have a piece of dynamic SQL I need to execute, I then need to store the result into a variable.

I know I can use sp_executesql but can\'t find clear e

10条回答
  •  孤街浪徒
    2020-11-22 16:51

    If you have OUTPUT parameters you can do

    DECLARE @retval int   
    DECLARE @sSQL nvarchar(500);
    DECLARE @ParmDefinition nvarchar(500);
    
    DECLARE @tablename nvarchar(50)  
    SELECT @tablename = N'products'  
    
    SELECT @sSQL = N'SELECT @retvalOUT = MAX(ID) FROM ' + @tablename;  
    SET @ParmDefinition = N'@retvalOUT int OUTPUT';
    
    EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT;
    
    SELECT @retval;
    

    But if you don't, and can not modify the SP:

    -- Assuming that your SP return 1 value
    create table #temptable (ID int null)
    insert into #temptable exec mysp 'Value1', 'Value2'
    select * from #temptable
    

    Not pretty, but works.

提交回复
热议问题