postgresql存储过程

本文介绍了一种使用SQL函数安全地向数据库表插入数据的方法。该方法通过设置参数operation为'insert'来确保只有插入操作可以生效,并在插入过程中遇到异常时进行回滚,保证数据的一致性和完整性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.为了防止误用,设置了一个参数operation,必须为insert时才生效;
2.在新增操作过程中,如果抛出异常中断,会回滚。
 
CREATE OR REPLACE FUNCTION fun_insert_into_tb_sys_vul_event2(operation text) RETURNS void AS
$$
BEGIN
    IF operation != 'insert' THEN
       RAISE EXCEPTION '参数错误!参数应该为insert!'; 
       RETURN ;
    else
    -- 为了避免重复录入,每次运行前先清空sys_vul_event表
    delete from sys_vul_event2;
    --RAISE EXCEPTION '删除失败!'; 
    --CVE披露事件 type=1
    insert into sys_vul_event2(sys_vul_id, event_date, type) select id, date_exposure, 1 as type from sys_vul where date_exposure is not NULL;
    --Google bulletin公开事件 type=2
    insert into sys_vul_event2(sys_vul_id, event_date, source, type) select id, date_bulletin, source, 2 as type from sys_vul where date_bulletin is not NULL;
    --提供修复patch事件 type=3
    insert into sys_vul_event2(sys_vul_id, event_date, type) select id, date_fixed, 3 as type from sys_vul where date_fixed is not NULL;
    --poc,exp公开事件 poc type=5;exp type=6
    insert into sys_vul_event2(sys_vul_id, event_date, type) select sys_vul_id, exposed_date, case when type='exp' then 6 when type='poc' then 5 end as type from security_matter;
    END IF;
    EXCEPTION WHEN others THEN  
    RAISE EXCEPTION '(%)', SQLERRM; 
    ROLLBACK;
END;
$$ LANGUAGE PLPGSQL; 

 rollback就相当于结束了,和return差不多。

转载于:https://www.cnblogs.com/miaoying/p/8494961.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值