简体   繁体   English

仅在满足特定条件时才执行insert语句

[英]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. 我想只在满足某个条件时才运行insert语句。 Is there a way to do that in pure sql? 有没有办法在纯SQL中做到这一点?

An example of what I'd like to do in pl/pgsql: 我想在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: 假设您要插入值42,那么如果没有一行,则以下内容仅插入一行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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