代码之家  ›  专栏  ›  技术社区  ›  BeardMagician

能否在PostgreSQL存储过程IF子句中执行WHERE子句?

  •  0
  • BeardMagician  · 技术社区  · 6 年前

    因此,我创建了一个触发器,在我的表中名为“Users”的行更新后触发,我只希望它更新 pg_notify 如果用户的“lat”和“lng”列与另一个lat和;液化天然气价值。我已经创建了一个SQL查询,其中包含一个WHERE子句,用于选择距离给定纬度和经度值一定距离内的所有用户,如下所示:

    SELECT *
    FROM users
    WHERE earth_box(ll_to_earth($1,$2), $3) @> ll_to_earth(lat, lng);
    

    WHERE子句仅选择纬度和经度在 $3 经纬度点米数 ($1, $2)

    CREATE OR REPLACE FUNCTION notify_on_user_location_update(channel text, specified_lat numeric, specific_lng numeric) RETURNS trigger AS $$
    DECLARE
      changed_lat numeric;
      changed_lng numeric;
      specified_radius numeric := 5000;
    BEGIN
      IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
        changed_lat = NEW.lat;
        changed_lng = NEW.lng;
      ELSE
        changed_lat = OLD.lat;
        changed_lng = OLD.lng;
      END IF;
    
    IF earth_box(ll_to_earth(specified_lat, specified_lng), specified_radius) @> ll_to_earth(changed_lat, changed_lng)
      PERFORM pg_notify(// notification specification here);
    ENDIF
      RETURN NEW;
    END;
    $$ LANGUAGE plpgsql;
    

    然而,这不起作用,因此它本质上只是伪代码。我能让这一切发生吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Dan    6 年前

    这个 IF 是一个条件,在PL中必须使用选择的可接受值。它必须有一个 THEN 条款和an END IF;

    在您的示例中,它没有令人钦佩的条件,并且 那么 缺少子句。此外,ENDIF带有空格和 ;

    IF
        (SELECT count(*)
        FROM users
        WHERE earth_box(ll_to_earth($1,$2), $3) @> ll_to_earth(lat, lng))>0
    THEN
        PERFORM pg_notify(// notification specification here);
    END IF;