简体   繁体   English

当数字存储为字符串时,从表中选择最高的数字?

[英]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! 我正在尝试使用C#.Net 4编写Windows窗体应用程序,它连接到SQL Server 2008数据库,并且我想从将数字存储为字符串的表中选择最高的数字!

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" 我也曾在select语句中尝试过Max(CAST(myField as Int)),但即使数据库为theCust的两行分别为10001和10002,它们都无法返回任何内容。错误i Get为“枚举未产生结果”

What am I doing wrong? 我究竟做错了什么?

I'm using the in built System.Data.SqlClient and if I just do a 我正在使用内置的System.Data.SqlClient,如果我只是做一个

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! 我只是用db中的int字段再次尝试了它,但仍然遇到相同的错误! Is Max the wrong thing to be using? Max用错了吗?

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.

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. 因为它比T-SQL中的内置ISNUMERIC()更好。

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. 然后,您可以使用此查询获取无误转换为整数类型的字符串集,并像使用TOP 1一样对其进行过滤。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM