How to return temporary table from stored procedure

前端 未结 6 1629
陌清茗
陌清茗 2020-12-15 07:31
CREATE PROCEDURE [test].[proc]
@ConfiguredContentId int,
@NumberOfGames int
AS
BEGIN
 SET NOCOUNT ON
 RETURN 
 @WunNumbers TABLE (WinNumb int)

    INSERT INTO @WunN         


        
6条回答
  •  难免孤独
    2020-12-15 08:05

    A temp table can be created in the caller and then populated from the called SP.

      create table #GetValuesOutputTable(
         ...   
      );
    
      exec GetValues; -- populates #GetValuesOutputTable
    
      select * from #GetValuesOutputTable;
    

    Some advantages of this approach over the "insert exec" is that it can be nested and that it can be used as input or output.

    Some disadvantages are that the "argument" is not public, the table creation exists within each caller, and that the name of the table could collide with other temp objects. It helps when the temp table name closely matches the SP name and follows some convention.

    Taking it a bit farther, for output only temp tables, the insert-exec approach and the temp table approach can be supported simultaneously by the called SP. This doesn't help too much for chaining SP's because the table still need to be defined in the caller but can help to simplify testing from the cmd line or when calling externally.

      -- The "called" SP
      declare
          @returnAsSelect bit = 0;
    
      if object_id('tempdb..#GetValuesOutputTable') is null
      begin
          set @returnAsSelect = 1;
          create table #GetValuesOutputTable(
             ...   
          );
      end
    
      -- populate the table
    
      if @returnAsSelect = 1
          select * from #GetValuesOutputTable;
    

提交回复
热议问题