【问题标题】:Dynamic SQL (where) in Firebird stored procedureFirebird 存储过程中的动态 SQL(where)
【发布时间】:2019-07-29 23:34:46
【问题描述】:

我有一个接收 2 个参数的 SP,P1P2,如下所示:

CREATE OR ALTER PROCEDURE MY_PROC (P1 varchar(10), P2 smallint = 1)
RETURNS (
    code      VARCHAR(10),
    name      VARCHAR(70),
    state     VARCHAR(2),
    situation VARCHAR(20)
AS 
    ...
    ...

而我需要根据P2参数生成where子句,像这样:

if (P2=1) then
    where (state='SP' and situation='stopped')  
elseif (P2=2)
    where (state='MG' and situation='moving')

如何在where子句中使用这种if语句?

【问题讨论】:

    标签: sql stored-procedures where-clause firebird firebird2.5


    【解决方案1】:

    对我来说,您的问题转化为 SQL 查询的 WHERE 子句中的简单 OR 条件:

    WHERE
       (:P2 = 1 AND state='SP' and situation='stopped')
       OR (:P2 = 2 AND state='MG' and situation='moving')
    

    【讨论】:

      【解决方案2】:

      GMB 的答案在大多数情况下都可以正常工作,但在更复杂的情况下,它的性能可能不太理想。另一种解决方案是动态构建查询字符串并使用execute statement 执行它:

      CREATE OR ALTER PROCEDURE MY_PROC (P1 varchar(10), P2 smallint = 1)
      RETURNS (
          code      VARCHAR(10),
          name      VARCHAR(70),
          state     VARCHAR(2),
          situation VARCHAR(20)
      AS 
      declare query varchar(2048);
      begin
        query = 'select ......';
        if (p2 = 1) then
          query = query || ' where (state=''SP'' and situation=''stopped'')';
        else if (p2 = 2) then
          query = query || ' where (state=''MG'' and situation=''moving'')';
      
        -- if you expect a single result
        execute statement query into code, name, state, situation;
      
        -- OR
      
        -- for multiple results
        for execute statement query into code, name, state, situation do
          suspend;
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多