sql - How to generate 5 digit increment number based on Zone? -
out put : if north "n00001 n00002 if south "s00001 s00002
here tried code
declare @zone varchar(20),@zoneid int,@id varchar(10) set @zone = 's' select @zoneid = cast(isnull(max(cast(replace(idno,@zone,'') numeric))+1,'00000') varchar) memberprofiles left(idno,1) = @zone set @id = @zone+cast(@zoneid varchar) select @id
but every time getting "s1" need "s00001"
how can generate zone wise number generation
this question "closed duplicate" candidate. but, there several flaws, think it's worth answer:
in database seem have column "idno" leading character marking zone. if true, should - if ever possible - change design. number , zone mark should reside in 2 columns. combination of them presentation issue
your
left(idno,1)
perform badly (read "sargability"). if there's index on idno, should better offidno ' + @zone + '%'
are sure, in "memberprofiles" there's 1 row
where
clause true? if not, number expect in "@zoneid" afterselect
?your
cast(isnull(max(cast(replace(idno,@zone,'') numeric))+1,'00000') ...
replaces leading "s" nothing, hoping there number left. you'll highest number (ok, answers point 3, still - uhm - hacky), still expect "null" you'd return "00000". cries better design loudly :-)you should try "set based" thinking, rather "procedural" thinking...
try this
create table #memberprofile(idno varchar(100),othercolumn varchar(100)); insert #memberprofile values('n3','test north 3'),('s24','test south 24'),('n14','test north 14') declare @zone varchar(20)='n'; select * ,zonecode + replace(str(number,5),' ','0') yournewpaddedcode #memberprofile cross apply ( select left(idno,1) zonecode ,cast(substring(idno,2,1000) int) number ) idno_in_parts zonecode=@zone; go --clean --drop table #memberprofile
the result
idno othercolumn zonecode number yournewpaddedcode n3 test north 3 n 3 n00003 n14 test north 14 n 14 n00014
Comments
Post a Comment