Adrian Adrian - 5 months ago 13
SQL Question

Select highest number from table when number strored 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?

Answer

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.