我有一个表tab
,其中包含列:
userid, usercode, value
我正在编写更新/插入表格的plpgsql
函数。
如果是用户ID和usercode存在我需要更新值
如果他们不需要插入新值
例如,如果表数据是:
userid, usercode, value
5 10 20
3 8 10
用于函数调用:
addvalue(5, 10 , 40)
addvalue(1, 12 , 40.5)
新数据将是:
userid, usercode, value
5 10 60
3 8 10
1 12 40.5
这是我的函数体:
CREATE OR REPLACE FUNCTION addvalue(xuserid integer, xusercode Integer,xvalue Numeric)
RETURNS integer AS
$BODY$
begin
insert into tab(userid,usercode,value) values(xuserid ,xusercode,xvalue);
return 1
end;
$BODY$
LANGUAGE plpgsql VOLATILE
了解我是否需要INSERT
或UPDATE
声明的最佳方式是什么?
我应该UPDATE
并检查它是否返回0(更新了0行),在这种情况下是INSERT
吗?或者我应该查询tab
表以查看是否userid = xuserid and usercode = xusercode
?
答案 0 :(得分:1)
begin
IF xuserid not in (select distinct userid from tab) THEN
insert into tab(userid,usercode,value) values(xuserid ,xusercode,xvalue);
ELSE
update tab
set value = value + xvalue
where userid = xuserid and usercode = xusercode
END IF;
-- return 1
end;
这是你想要做的吗?