【问题标题】:Postgres if statement inside function inserting valuesPostgres if语句在函数内插入值
【发布时间】:2017-10-16 14:22:54
【问题描述】:

是否可以使此功能正常工作?我在 Postgres 函数的 Insert Into 查询中有 If 语句。

你有什么方法?

    CREATE FUNCTION proc_api_consumer_audit_insert()
    RETURNS TRIGGER AS $api_consumer$
    BEGIN
        INSERT INTO api_consumer_audit(api_consumer_id, change_type, changed_by, changed_date, business_id_old, business_id_new, name_old, name_new, api_callback_url_old, api_callback_url_new, application_base_url_old, application_base_url_new, authorization_callback_url_old, authorization_callback_url_new, status_old, status_new) 
        VALUES(NEW.id, 'INSERT', (IF NEW.created_by=null THEN CURRENT_USER ELSE NEW.created_by END IF;), CURRENT_TIMESTAMP, null, NEW.business_id, null, NEW.name, null, NEW.api_callback_url, null, NEW.application_base_url, null, NEW.authorization_callback_url, null, NEW.status);
        RETURN NEW;
    END;
    $api_consumer$ LANGUAGE plpgsql;

【问题讨论】:

    标签: postgresql if-statement sql-insert plpgsql


    【解决方案1】:

    SQL 中没有IF。一般来说,人们会使用 CASE 表达式,但在你的情况下,coalesce() 要短得多:

    INSERT INTO api_consumer_audit(...) 
    VALUES (NEW.id, 
            'INSERT', 
            coalesce(new.created_by, current_user),
            ...);
    

    与 CASE 表达式相同的是:

    INSERT INTO api_consumer_audit(...) 
    VALUES (NEW.id, 
            'INSERT', 
            case 
               when new.created_by IS NOT NULL then new.created_by
               else current_user
            end,
            ...);
    

    【讨论】:

    • 当我调用 sql 插入查询时,coalesce 不起作用:INSERT INTO api_consumer (business_id, type, status, description, created_by, created_date, modified_by, modified_date, name, origin_country, license_authority_name, registration_date, api_callback_url, application_base_url, authorization_callback_url, address, local_address, license) VALUES ('101', 'PSD2', 'NEW', 'TEST OF TRIGGER ON INSERT', 'kk', CURRENT_TIMESTAMP, 'gg', null, 'SPRAWDZAM_COS', 'PL', null, null, null, null, null, 1, 1, 1); - 它仍然显示 mi 不正确的用户
    • @xross 您在第一条评论中添加的代码中没有coalesce()
    • 好的,无论如何它有效。我在要在 DB 中完成的第一条评论中写了插入 - 这不是函数中的查询
    猜你喜欢
    • 2020-07-05
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    相关资源
    最近更新 更多