Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In SQL Server database I there is a field which datatype is varchar(20).
Every data insert with a prefix EMB. Suppose I have three data in the field. These are
MBA00001
MBA00002
MBA004042
MBA00500

Here the max number is MBA004042 but the query
select max(TraRentAsset) as TraRentAsset from RentInfo brings MBA00500.
How can I define the MBA004042 and increment 1. The result will be now MBA004043.
Please help me. I will be very grateful to you.
Posted
Updated 2-Dec-14 17:18pm
v2

SQL
select top 1 TraRentAsset from RentInfo
order by cast(SUBSTRING(TraRentAsset, 4, LEN(TraRentAsset)) as int) desc


DEMO[^]
 
Share this answer
 
v2
Comments
Sumon562 2-Dec-14 1:06am    
It shows conversion error
DamithSL 2-Dec-14 1:10am    
I'm not sure about your inputs. do you have null values in your column? or values not having above format?
Use this..
SQL
select max(substring(isnull(TraRentAsset,'MBA0'),4,len(isnull(TraRentAsset ,'MBA0'))))+1 
 
Share this answer
 
Comments
Sumon562 2-Dec-14 22:22pm    
It arises the following error
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'T00006' to data type int.
/\jmot 3-Dec-14 0:05am    
T00006?
where you get this??
check this

SQL
Create table #file(col1 varchar(20))
insert into #file select 'MBA00001'
insert into #file select 'MBA00002'
insert into #file select 'MBA004042'
insert into #file select 'MBA00500'

select  'MBA'+Convert(Varchar(20),MAX(convert(int,REPLACE(col1,'MBA','')))) from #file
 
Share this answer
 
Comments
Sumon562 2-Dec-14 22:21pm    
It shows the following error
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'RENT00003' to data type int.
Shweta N Mishra 5-Dec-14 3:52am    
it works for me what you code you have written ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900