函数(Function)

invoices表格:

创建一个函数

DELIMITER $$
create function get_risk_factor_for_client
(
    client_id int
)
        -- 设置函数返回值的类型
returns integer
        -- 设置函数属性
        -- DETERMINISTIC -- 确定性
        reads sql data -- 读取sql数据
        -- modifies sql data -- 插入、更新、或删除函数
begin
    declare risk_factor decimal(9,2) default 0;
    declare invoices_total decimal(9,2);
    declare invoices_count int;
    
    select count(*),sum(invoice_total)
    into invoices_count,invoices_total
    from invoices i
    where i.client_id=client_id;
    
    set risk_factor=invoices_total/invoices_count*5;
        
    -- 返回风险值
    return ifnull(risk_factor,0);
end$$
DELIMITER ;

调用函数

select client_id,
       name,
       get_risk_factor_for_client(client_id) as risk_factor
from clients;

posted @ 2020-12-15 16:06  醴酒微甜  阅读(154)  评论(0编辑  收藏  举报