PostgreSQL 创建随机生成颜色代码函数

今天想渲染3D地图的时候,随机从数据库生成颜色代码用于前端渲染。自己写了函数生成颜色代码


创建函数的SQL语句如下

create function hexColor() returns varchar as $$
with cte1 as (
select round(random()*15) as hex1,
round(random()*15) as hex2,
round(random()*15) as hex3,
round(random()*15) as hex4,
round(random()*15) as hex5,
round(random()*15) as hex6
),
cte2 as (
select case when hex1 = 10 then 'A'
when hex1 = 11 then 'B'
when hex1 = 12 then 'C'
when hex1 = 13 then 'D'
when hex1 = 14 then 'E'
when hex1 = 15 then 'F'
else 'F' end as hex1h,
case when hex2 = 10 then 'A'
when hex2 = 11 then 'B'
when hex2 = 12 then 'C'
when hex2 = 13 then 'D'
when hex2 = 14 then 'E'
when hex2 = 15 then 'F'
else 'F' end as hex2h,
case when hex3 = 10 then 'A'
when hex3 = 11 then 'B'
when hex3 = 12 then 'C'
when hex3 = 13 then 'D'
when hex3 = 14 then 'E'
when hex3 = 15 then 'F'
else 'F' end as hex3h,
case when hex4 = 10 then 'A'
when hex4 = 11 then 'B'
when hex4 = 12 then 'C'
when hex4 = 13 then 'D'
when hex4 = 14 then 'E'
when hex4 = 15 then 'F'
else 'F' end as hex4h,
case when hex5 = 10 then 'A'
when hex5 = 11 then 'B'
when hex5 = 12 then 'C'
when hex5 = 13 then 'D'
when hex5 = 14 then 'E'
when hex5 = 15 then 'F'
else 'F' end as hex5h,
case when hex6 = 10 then 'A'
when hex6 = 11 then 'B'
when hex6 = 12 then 'C'
when hex6 = 13 then 'D'
when hex6 = 14 then 'E'
when hex6 = 15 then 'F'
else 'F' end as hex6h from cte1)
select '#' || ltrim(hex1h) || ltrim(hex2h) || ltrim(hex3h) || ltrim(hex4h) || ltrim(hex5h) || ltrim (hex6h) from cte2;
$$ LANGUAGE SQL;

调用如下

update tablename set color = hexColor();

Jishuai.Wang wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创分享,您的支持将鼓励我继续创作!
0%