CASE / IF条件下RAISE异常的Postgresql UPDATE语法错误

时间:2019-09-26 06:51:49

标签: sql postgresql sql-update sqlexception

我对编写具有CASE(或IF)条件的Postgresql UPDATE查询感到困惑。

预期的行为:我必须提出一个例外,并且如果一个特定字段不为null,则不要进行更新。 当前行为:我尝试使用CASE和IF条件,但是每次遇到语法错误时:SQL错误[42601]:错误:在“异常”或附近出现语法错误。 想法:也许可以通过向表添加约束来实现相同的结果?

    UPDATE public.SomeTable 
SET Title = (
    case when EndDate IS null
        THEN 'new title' 
        ELSE raise exception 'Cannot update entity if EndDate is not null'
    end),
    Description = (
    case when EndDate IS null
        THEN 'new description' 
        ELSE raise exception 'Cannot update entity if EndDate is not null'
    end)
WHERE Id=4 

版本: x86_64-pc-linux-gnu上的PostgreSQL 11.5(Debian 11.5-1.pgdg90 + 1),由gcc(Debian 6.3.0-18 + deb9u1)编译6.3.0 20170516,64位

2 个答案:

答案 0 :(得分:1)

我认为做到这一点的唯一相对方便的方法是使用可更新的视图:

create view vw_sometable as
    select t.*
    from sometable t
    where endDate is null
    with check option;

然后您将插入视图,而不是基础表。

您可以通过授予视图上的update而不是基础表的权限来进一步优化,因此所有update都需要通过视图。

好吧,另一个方法不会返回错误,但是不会更新行。只需在where子句中包含条件即可:

UPDATE public.SomeTable 
    SET Title = 'new title',
        Description = 'new description' 
WHERE Id = 4 AND EndDate is null';

您可以添加后续逻辑来检查是否有任何行被更新并在那里引发错误。

答案 1 :(得分:0)

结束后删除案例

UPDATE public.SomeTable 
SET Title = (
    case when EndDate IS null
        THEN 'new title' 
        ELSE 'Cannot update entity if EndDate is not null'
    end ),
    Description = (
    case when EndDate IS null
        THEN 'new description' 
        ELSE 'Cannot update entity if EndDate is not null'
    end )
WHERE Id=4