Firebird 存储过程中的动态 SQL (where)

Dynamic SQL (where) in Firebird stored procedure

我有一个接收 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 查询的 WHERE 子句中的一个简单 OR 条件:

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

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