首先创建这个函数应该是没问题的吧
但是由于这个函数中包含了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;
代码看不出什么问题,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
写的很好,很简洁。
报的是什么错误 贴出来!~