Click here to Skip to main content
15,890,609 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a identity filed OrderNo in my table Orders the datatype in nvarchar
I have the orderNo 20000, T20000
How to autoincrement with MAX function i need 20001 or T20001

What I have tried:

select 'T' + CONVERT(VARCHAR(10),max(OrderNo)+1)AS OrderNo  from tblOrderMaster
Posted
Updated 2-Sep-18 22:36pm

If you want to persist the OrderNumber with the 'T' preceding it in your database then you will need a separate column to store it in (this is why you are getting your "I am getting error like this "Conversion failed when converting the nvarchar value 'T20001' to data type int" error).

You have already stated that OrderNo is an Identity field so there is no need to use MAX() - in fact you should never use that as a method for generating a "unique" id (there is no guarantee it will be unique in a multi-user database).

To get your order number with the preceding "T" just use
SQL
select 'T' + CAST(OrderNo AS VARCHAR) AS OrderNoWithPrefix from tblOrderMaster
To be honest there is no need to persist this value on the database as it appears to be a display only feature - just add the T when you need it.
 
Share this answer
 
v2
 
Share this answer
 
SQL
select 'T' + CONVERT(VARCHAR, MAX(OrderNo)+1, 103) AS OrderNo from tblOrderMaster
 
Share this answer
 
Comments
Member 13569764 2-Sep-18 3:36am    
I am getting error like this "Conversion failed when converting the nvarchar value 'T20001' to data type int"
select 'T' + CONVERT(VARCHAR(10),max(OrderNo)+1)AS OrderNo  from (SELECT REPLACE(OrderNo,'T','')AS OrderNo from @tblOrderMaster) Final
 
Share this answer
 

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