写一段pl⼀sql程序代码,当向表中插入数据时,先查询是否存在相同主键,如果不存在则插入,存在则提醒。

2025-03-24 20:13:59
推荐回答(4个)
回答1:

首先创建这个函数应该是没问题的吧
但是由于这个函数中包含了DML语句在使用过程中会存在很多问题
首先最好的建议是使用触发器
另外如果要想在函数中使用DML语句的话,建议增加pragma autonomous_transaction;和commit;那么你的函数建议修改为如下(表名和列名修改对照修改过来):

create or replace function fun_charge_s(x in number) return number as
pragma autonomous_transaction; ----
s_warn number;

begin
select count(*) into s_warn from test2 where year = x;
if nvl(s_warn, 0) = 0 then
insert into test2 (year) values (x);
commit; ----
dbms_output.put_line('可以插入数据。');
return 0;

else
dbms_output.put_line('存在相同sno,不可以插入。');
return s_warn;
end if;

exception
when others then
dbms_output.put_line(sqlerrm || sqlcode);
end;

回答2:

代码看不出什么问题,count(*) 必然会返回值的,不需要用nvl函数 直接 if s_warn=0 then ..
不要用count(*) 很耗费资源的,要用exists
select case when exists(select * from s_warn where sno=x) then 1 else 0 end into s_warm from dual

回答3:

写的很好,很简洁。

回答4:

报的是什么错误 贴出来!~