【问题标题】:Use stored procedure in select在选择中使用存储过程
【发布时间】:2014-01-28 10:10:54
【问题描述】:

考虑一个返回表的存储过程:

DELIMITER //
CREATE PROCEDURE GetLegalAnimals (IN prop VARCHAR(128))
    BEGIN
        -- Lots of fiddling with temporary tables here
        SELECT
            animal, hit_points, terrain, weight, height, girth, attack, defence, quest
        FROM
            temp_animals;
    END //
DELIMITER ;

我现在想过滤返回表的结果:

SELECT animal, terrain FROM GetLegalAnimals('rodent') WHERE hit_points<42;

上面的查询没有运行,因为它不是有效的 MySQL 语法。有没有办法执行这样的查询?我不想为每个(无限)条件实现单独的GetLegalAnimals_* 过程,并且我不想在过程中添加其他参数,因为存在无限的 SELECT 和 WHERE 子句排列。

请注意,存储过程使用参数,因此尽管 SO 社区有一些 creative solutions,但视图不是合适的解决方案。

【问题讨论】:

  • 我认为您需要的是视图,而不是存储过程。 (或者可能是一个函数)
  • 据我所知,在 select 语句中无法调用 SP。您必须使用临时表来存储 SP 的结果并从该临时表中进行选择。
  • 除非你的条件产生多个结果,你可以试试select .... into @_animal, ... into @_terrain, ... where somX='rodent' and hit_points &lt; 42。你可以从你的脚本语言中读取这些变量。
  • @Ravinder:我不确定我是否关注你。您能否发布一个指向描述您的方法的页面的链接?谢谢!
  • 谢谢,我正在查看意见。

标签: mysql sql select stored-procedures


【解决方案1】:

如果你想使用整张桌子,你需要一个VIEW。首先创建视图

USE `yourdatabase`;
CREATE  OR REPLACE VIEW `GetLegalAnimals` AS
-- Lots of fiddling with temporary tables here
        SELECT
            animal, hit_points, terrain, weight, height, girth, attack, defence, quest
        FROM
            temp_animals;
;

然后就可以查询了

SELECT animal, terrain FROM GetLegalAnimals WHERE hit_points < 42;

【讨论】:

  • 谢谢,但是存储过程需要一个参数并且视图不支持参数。尽管已经提出了一些针对using a parameter with a view 的解决方案,但它们都是 hacky!
  • 您好,您发布的存储过程中从未使用过参数?
  • 当然,您可以使用WHERE。那还不够吗? SELECT animal, terrain FROM GetLegalAnimals WHERE animal='rodent' AND hit_points &lt; 42;
  • 是的,使用了参数。
【解决方案2】:

使用view 代替存储过程

CREATE VIEW view_name AS
-- Lots of fiddling with temporary tables here
        SELECT
            animal, hit_points, terrain, weight, height, girth, attack, defence, quest
        FROM
            temp_animals;

【讨论】:

  • 谢谢,但是存储过程需要一个参数并且视图不支持参数。尽管已经提出了一些针对using a parameter with a view 的解决方案,但它们都是 hacky!
  • @dotancohen 是的,视图不支持参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 2010-12-15
  • 1970-01-01
  • 2015-04-01
  • 2017-08-04
  • 1970-01-01
相关资源
最近更新 更多