简体   繁体   中英

execute insert statement only if a certain condition is met

I'd like to run an insert statement only if a certain condition is met. Is there a way to do that in pure sql?

An example of what I'd like to do in pl/pgsql:

CREATE OR REPLACE FUNCTION set_search_lock (
    userid     IN   integer,
)
    RETURNS boolean AS $body$


DECLARE
BEGIN

    PERFORM 'A' FROM LOCK_TABLE WHERE USERID = userid LIMIT 1;

    IF NOT FOUND THEN
        INSERT INTO LOCK_TABLE (USERID) VALUES (userid);
        RETURN true;
    ELSE
        RETURN false;
    END IF;


END;
$body$
LANGUAGE PLPGSQL;

Assuming you want to insert the value 42, then the following will only insert a row if there isn't one already:

insert into lock_table (userid) 
select 42
where not exists (select 1 from lock_table where userid = 42);

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