域名預(yù)訂/競(jìng)價(jià),好“米”不錯(cuò)過
這篇文章主要介紹了postgresql 實(shí)現(xiàn)replace into功能的代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧。
PostgreSQL 9.5-
使用函數(shù)或with實(shí)現(xiàn)
create table test(id int primary key, info text, crt_time timestamp);
with upsert as (update test set info='test',crt_time=now() where id=1 returning *) insert into test select 1,'test',now() where not exists (select 1 from upsert where id=1);
PostgreSQL 9.5+
PostgreSQL 9.5 引入了一項(xiàng)新功能,UPSERT(insert on conflict do),當(dāng)插入遇到約束錯(cuò)誤時(shí),直接返回,或者改為執(zhí)行UPDATE。
INSERT INTO table_name VALUES() ON conflict (唯一索引字段) DO
UPDATE ...
補(bǔ)充:PostgreSQL中select into用法總結(jié)
在普通的sql中,postgresql支持seelct......into......
但是動(dòng)態(tài)調(diào)用時(shí)候不支持select......into......
比如:
create or replace FUNCTION test () RETURNS void AS
$body$
DECLARE
toalnum int;
BEGIN
execute 'select sum(colname) into totalnum';
return;
END;
$body$
LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;
以上情況會(huì)報(bào)錯(cuò)。。。。。
因該修改為如下
create or replace FUNCTION test () RETURNS void AS
$body$
DECLARE
toalnum int;
BEGIN
execute 'select sum(colname)' into totalnum;
return;
END;
$body$
LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;
文章來源:腳本之家
來源地址:https://www.jb51.net/article/204868.htm
申請(qǐng)創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!