postgreSQL自动生成随机数值

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;

参考文档:
https://yq.aliyun.com/articles/228275
https://blog.csdn.net/pg_hgdb/article/details/79227924

你可能感兴趣的:(数据库)