Click here to Skip to main content
15,909,953 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

I have a table column which is my primary key. The column value starts at 10000 . when a data is inserted to the table the column value will be appended with 'POD' ie it will be like POD10000,POD10001,POD10002 etc...It was working fine .But due to some modifications
in a certain page I had to insert an extension '-1','-2' .Now whenever I insert a new value I get an error "
Conversion failed when converting the varchar value '10001-1' to data type int
".

So my question how can I find the next highest value excluding the extension '-'.
Suppose if the values in coulmn is
POD10000
POD10000-1
POD10000-2
POD10000-3
POD10004
POD10005
POD10005-1


I need to get the value as 10006.Please help me.

What I have tried:

select isnull(max(CONVERT(INT,substring(col1,4,11)))+1,0) as col1 from tab_1


Here I will get the next value as 10006 if there are no values with '-'.How to get the next highest value if there is '-'.
Any help will be really appreciated.Thanks in advance.
Posted
Updated 25-Oct-17 3:25am

1 solution

'10000-1' can not be converted to INT (obviously)...
If you want keep them in order (10000, 10000-1, 10000-2, 10001, 10002) you have two options:
1. Use floating point and replace the '-' to '.'... - it gives 10000, 10000.1, 10000.2, 10001, 10002
2. Replace the '-' with '.' and multiple by 10 (or 100 if you have more then one digit after the '-'...) - it gives 100000, 100001, 100002, 100010, 100020
 
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