Search code examples
mysqlsqlselectstored-proceduresresultset

Is there any way to store a SELECT result and output the resultset at the same time?


In the next sample procedure, can I output the row from the queried table as a procedure resultset, and at the same time store a single field or some fields in a variable (similarly as when I use SELECT INTO)? The only way I can imagine is repeating the query.

CREATE PROCEDURE `Panel_TerminalesForm`(IN idTerminal INT)
  BEGIN
    declare somefield INT:
    -- this select statement returns the found row as a resultset
    SELECT terminales.*
    FROM terminales
    WHERE id_terminal = idTerminal;
    -- but I also want to have here a table field inside the variable somefield
    -- do some manipulation with somefield...
END;

Solution

  • If i understand you correctly, you need to create a temporary table, then you can manipulate the temporary the way you want.

    MySQL:

        CREATE PROCEDURE `Panel_TerminalesForm`(IN idTerminal INT)
            BEGIN
              declare somefield INT
    
              CREATE TEMPORARY TABLE SampleTempTable
              SELECT * INTO SampleTempTable FROM terminales WHERE id_terminal = idTerminal;
    
              -- output the resultset
              SELECT * FROM SampleTempTable   
    
              -- read the variables you want
              SELECT field INTO somefield FROM SampleTempTable   
    
              -- Drop the temp table
              DROP TEMPORARY TABLE SampleTempTable
        END;
    

    http://www.mysqltutorial.org/mysql-temporary-table/

    SQL Server:

        CREATE PROCEDURE `Panel_TerminalesForm`(IN idTerminal INT)
            BEGIN
              declare somefield INT
    
              SELECT terminales.* 
              INTO #tempSample FROM terminales
              WHERE id_terminal = idTerminal;
    
              SELECT * FROM #tempSample
    
              -- Drop the temp table
              DROP TABLE #tempSample
        END;
    

    Note: Drop the temp table after using it to avoid errors.