Generate unique string in sql server 2012 -
i have table
create table #agency ( agencyid int primary key identity(1,1), agencyname varchar(100), agencycode varchar(50) )
i want generate unique agency code while inserting table...agency code should consists of alphabets ..no numbers or special characters
thank you
you can simple casting id varchar , replacing every digit letter (or combination).
1=a, 2=b, etc..
so, long ids unique, code be.
snippet like:
replace(replace(replace(replace(replace(replace(replace(replace(replace(replace( cast(agencyid varchar(50)) ,'1','a'),'2','b'),'3','c'),'4','d'),'5','e'),'6','f'),'7','g'),'8','h'),'9','i'),'0','j')
if want during insert, can use ident_current('tablename') value inserts identity column.
insert agency (agencyname, agencycode) select 'name001', replace(replace(replace(replace(replace(replace(replace(replace(replace(replace( cast(ident_current('agency') varchar(50)) ,'1','a'),'2','b'),'3','c'),'4','d'),'5','e'),'6','f'),'7','g'),'8','h'),'9','i'),'0','j') ;
creating function converts number string and/or computed column might prettier use.
demo using function , computed columns
edit: