首页 > 杂文归档 正文
postgreSQL自动生成随机数值的实例

 2021-01-12 12:20:02     

1、 随机生成身份证
新建一个函数,用来生成身份证号码,需要输入两个日期参数


create or replace function gen_id(
a date,
b date
)
returns text as $$
sele

1、 随机生成身份证

新建一个函数,用来生成身份证号码,需要输入两个日期参数

create or replace function gen_id(  
 a date,  
 b date  
)   
returns text as $$  
select lpad((random()*99)::int::text, 2, '0') ||   
    lpad((random()*99)::int::text, 2, '0') ||   
    lpad((random()*99)::int::text, 2, '0') ||   
    to_char(a + (random()*(b-a))::int, 'yyyymmdd') ||   
    lpad((random()*99)::int::text, 2, '0') ||   
    random()::int ||   
    (case when random()*10 >9 then 'X' else (random()*9)::int::text end ) ;  
$$ language sql strict; 

生成10个随机身份证号码

select gen_id('1900-01-01', '2017-10-16') from generate_series(1,10); 

生成十万条随机身份证号码

insert into testpg SELECT generate_series(1,100000) as xm, gen_id('1900-01-01', '2017-10-16') as num;

补充:postgreSql的id设置自动生成随机24位数字与字母组合(uuid)

我就废话不多说了,大家还是直接看代码吧~

@Id
@GeneratedValue(generator="system_uuid")
@GenericGenerator(name="system_uuid",strategy="uuid")
@Column(name = "ID", unique = true, nullable = false, length = 24)
public String getId() {
  return this.id;
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:http://www.yuepc.com/a/1684.html

http://www.yuepc.com 为 “沈一博客” 唯一官方服务平台,请勿相信其他任何渠道。