Adrian
Adrian

Reputation: 1149

Select highest number from table when number stored as string?

I'm trying to write a windows forms app in C# .Net 4 it connects to a SQL Server 2008 database and I want to Select highest number from a table where the number is stored as string!

string SQL = "select MAX(CONVERT(int, myField)) from myTable where myCode = '" + theCust + "'";

I have also tried Max(CAST(myField as Int)) in the select statement but both fail to return anything even though the Database has for the theCust two rows with 10001 and 10002. The Error i Get is "Enumeration yielded no results"

What am I doing wrong?

I'm using the in built System.Data.SqlClient and if I just do a

string SQL = "select myField from myTable where myCode = '" + theCust + "'";

it returns both numbers as strings. I know I could sort them in code but if the Database gets large that would not be a good approach!

I just tried it again with an int Field in the db and still got the same error! Is Max the wrong thing to be using?

Upvotes: 2

Views: 1882

Answers (2)

Igor Micev
Igor Micev

Reputation: 1662

Have this function in your database(s):

CREATE FUNCTION dbo.IsAllDigits (@MyString VARCHAR(8000))
RETURNS TABLE AS
RETURN (
         SELECT CASE 
                WHEN @MyString NOT LIKE '%[^0-9]%'
                THEN 1
                ELSE 0
                END AS IsAllDigits
        )

because it's better than the in-build ISNUMERIC() in T-SQL.

Then you can use this query to get set of strings that convert to integer types without errors, and filter them like with TOP 1.

SELECT TOP 1 MyColumn AS TheMax
FROM MyTable
WHERE IsAllDigits(MyColumn)=1
ORDER BY MyColumn DESC

Upvotes: 1

Evan
Evan

Reputation: 1737

You can try it like this:

SELECT TOP 1 CAST(MyColumn AS int) AS TheMax
FROM MyTable
ORDER BY TheMax DESC

So (using the sloppy method, always paramaterize!)

String sql = "SELECT TOP 1  CAST(MyColumn AS int) AS TheMax FROM MyTable WHERE MyParam = '" + param + "' ORDER BY TheMax Desc";
//Fill DataAdapter/DataReader etc.

Upvotes: 5

Related Questions