简体   繁体   中英

Postgresql UPDATE syntax error on RAISE exception in CASE / IF condition

I am confused with writing Postgresql UPDATE query with CASE (or IF) condition.

Expected behavior: I have to raise an exception and do not do update if one specific field is not null. Current behavior: I tries CASE and IF conditions, but every time I got syntax error: SQL Error [42601]: ERROR: syntax error at or near "exception". Thoughts : maybe there is a way to achieve same result with adding constraint to table?

    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 

Version: PostgreSQL 11.5 (Debian 11.5-1.pgdg90+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit

The only relatively convenient way I can think to do this uses updatable views:

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

You would then insert into the view, rather than into the underlying table.

You can further refine this by giving update permissions on the view but not on the underlying table, so all update s need to go through the view.

Well, another method would not return an error, but it would not update the rows. Just include the condition in the where clause:

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

You could add subsequent logic to check if any rows are updated and raise the error there.

remove case after end

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM