我想仅在满足某个条件时才运行insert语句。有没有办法在纯sql中做到这一点?
我想在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;
答案 0 :(得分:3)
假设您要插入值42,那么如果没有一行,则以下内容只会插入一行:
insert into lock_table (userid)
select 42
where not exists (select 1 from lock_table where userid = 42);