开发者

auto generate custom id with sql

I am relatively new to sql and databases and would like some help in the following topic. I have the following table: (junior male -> jm, junior female -> jf, adult male -> am, adult female-> af)

id    code     name    
1     jm       john       
2     am       patrick    
3     af       jane       
4     jm       peter      
5     jm       derrick    
6     af       mary       
7     jf       jessica  

and would like to create a field inside the table as a reference which is made up of the code and autoincrement digits in this way:

id      code     name     reference

1     jm     开发者_如何转开发  john       jm001

2     am       patrick    am001

3     af       jane       af001

4     jm       peter      jm002

5     jm       derrick    jm003

6     af       mary       af002

7     jf       jessica    jf001

can anyone give me some tips on how to do this? Thank you


First, ask yourself "Why?" as in Martin's comment. If you have a good answer to this question, then a sequence for each type is probably what you are looking for. For example in Oracle:

CREATE SEQUENCE jm_seq START WITH 1 INCREMENT BY 1 NOMAXVALUE NOCYCLE;
CREATE SEQUENCE jf_seq START WITH 1 INCREMENT BY 1 NOMAXVALUE NOCYCLE;
CREATE SEQUENCE am_seq START WITH 1 INCREMENT BY 1 NOMAXVALUE NOCYCLE;
CREATE SEQUENCE af_seq START WITH 1 INCREMENT BY 1 NOMAXVALUE NOCYCLE;

Then, you can use these when you enter the specific types. For example, to enter a junior male, you'd use:

Insert into table_name 
  values (id_seq.nextVal, 'jm', 'Bart', 'jm' || jm_seq.nextVal);

Also, this will not give you leading zeros as in your example, so look into formatting your number if that is needed.


You can make use of this following Code in-order to arrive to your desired result... Cheers...

drop table if exists Custom_id_Dynamic;
create table Custom_id_Dynamic (id int primary key auto_increment , Code varchar(20), 
Name varchar(20), Reference varchar(20));


drop procedure if exists Dynamic_id;

set @index:=0;
set @jm:=0;
set @unknown:=0;
set @am:=0;
set @af:=0;
set @jf:=0;

delimiter $$

create procedure Dynamic_id(
in code_new varchar(20), in name_new varchar(20)
)

begin
set code_new=lower(code_new);
if code_new='jm' then set @jm:=@jm+1, @index:=@jm;
elseif code_new='am' then set @am:=@am+1, @index:=@am;
elseif code_new='af' then set @af:=@af+1, @index:=@af;
elseif code_new='jf' then set @jf:=@jf+1, @index:=@jf;
else set @unknown:=@unknown+1, @index:=@unknown;
end if;
insert into Custom_id_Dynamic (Code, Name, Reference) 
values (code_new, name_new, concat(code_new, lpad(@index,3,0)));
end;



call Dynamic_id('jm','john');
call Dynamic_id('am','patrick');
call Dynamic_id('af','jane');
call Dynamic_id('jm','peter');
call Dynamic_id('jm','derrick');
call Dynamic_id('af','mary');
call Dynamic_id('jf','jessica');


select * from Custom_id_Dynamic;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜