postgresql 函数根据 IF ELSEIF 条件更新每一行

postgresql function to update each row based on IF ELSEIF conditional

我正在尝试创建一个将由 cron 作业每 30 分钟执行一次的 postgresql 函数。此函数将执行 if else 条件并根据当前时间和其他列值更新列。

我总是在 IF 语句的开头遇到语法问题,无法理解为什么:

ERROR:  syntax error at or near "scheduled_active_start"
LINE 7:      IF scheduled_active_start <= executionTime AND schedule...
                ^
********** Error **********

ERROR: syntax error at or near "scheduled_active_start"
SQL state: 42601
Character: 144

这是我要创建的 postgresql 函数:

CREATE OR REPLACE FUNCTION updatePostActivity()   RETURNS void AS $$

DECLARE
    executionTime timestamp = Now();
BEGIN
    UPDATE  post
        IF scheduled_active_start <= executionTime AND scheduled_active_end > executionTime AND is_active != true THEN
             SET is_active = true;
        ELSEIF  scheduled_active_end <= executionTime AND is_active != false THEN 
            SET is_active = false;
        END IF;
END;
$$   
LANGUAGE plpgsql VOLATILE 

UPDATE statement clearly stays that there is nothing between UPDATE and SET keywords except the table definition. The IF statement is absent in the SQL at all (as I know). Use CASE 语句的语法改为:

UPDATE post SET
  is_active = CASE 
    WHEN scheduled_active_start <= executionTime AND scheduled_active_end > executionTime AND is_active != true THEN true
    WHEN scheduled_active_end <= executionTime AND is_active != false THEN false
  END
WHERE -- Filter to avoid updating whole table
  (scheduled_active_start <= executionTime AND scheduled_active_end > executionTime AND is_active != true) OR
  (scheduled_active_end <= executionTime AND is_active != false);

PS:is_active != true 等于 not is_activeis_active != false 等于 is_active