Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table where has a field "billNo" as varchar. Table has two kinds of data. One kind is non number and other kind is number type. Like the following-

Table name: billinfo
Field and data:
VB
billNo
--------- 
1004-0058
1004-0059
1004-0060
1004-0061
1004-0062
1004-0063
1004-0064
1004-0065
1004-0066
01
02
03
04
05
06
07
08


I need a sql what return max number from the field "billNo" from the table billinfo. Remember- The non number value no need to consider. I need the return value is 08.

Please ..
Posted
Comments
CHill60 8-Apr-14 8:37am    
'08' would not be the maximum number from your sample - are you saying that the max should ignore anything like '1004-0060' etc?

Try This :
temp is table name and number is column name

SQL
select max(Convert(int, number)) from temp where isnumeric(number) = 1
 
Share this answer
 
You can't really do that: SQL doesn't have a TryParse method which lets you attempt to convert a string to a number and continue if it fails.
And you can't use MAX on a string field and get numeric results unless the strings are all the same length and padded with leading zeros, as a string comparison stops at the first character difference and uses that as the basis for the whole comparison.

The best solution is to use two different separate fields for this: one sting based, and one numeric. There is no "nice" solution with mixed data such as you show.
 
Share this answer
 
Comments
Maciej Los 8-Apr-14 10:02am    
Really?
TRY_PARSE[^]
OriginalGriff 8-Apr-14 10:48am    
Really: TRY_PARSE is SQL 2012 onward only.
It doesn't exist in "most" SQL installations...
Maciej Los 8-Apr-14 12:00pm    
I know it ;)
Maciej Los 8-Apr-14 10:09am    
Useful solution.
A 4, because of above comment.
Have a look at my answer ;)
try this-


SQL
Select MAX( CAST(billNo as int)) from
billInfo
Where billNo NOT LIKE '%-%'

or
SQL
Select MAX(numberBillNo)
from (
SELECT Cast(billNo as int) as numberBillNo  FROM billInfo
Where billNo NOT LIKE '%-%'
) as tmp
 
Share this answer
 
If you can find a way of ordering the billno you could try
SQL
SELECT TOP 1 billNo from billinfo ORDER BY billNo DESC
but as I mentioned in my comment above you might want to exclude the other "style" of entry with
SQL
WHERE billNo NOT LIKE '-'

Either way you really need to reconsider your table schema
 
Share this answer
 
OriginalGriff suggested the idea. Thanks, Paul!

Have a look at TRY_PARSE[^] method!
Note: This method is available starting from MS SQL Server 2012!
As you can see, it possible to get numeric format depends on local culture.
 
Share this answer
 
v2

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