有没有办法存储SELECT结果并同时输出结果集?

时间:2015-10-14 08:17:50

标签: mysql sql select stored-procedures resultset

在下一个示例过程中,我可以将查询表中的行作为过程结果集输出,同时在变量中存储单个字段或某些字段(类似于我使用SELECT INTO时)?我能想象的唯一方法是重复查询。

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;

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你需要创建一个临时表,然后你可以按照你想要的方式操作临时表。

<强> 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;

注意:使用后删除临时表以避免错误。