2012-01-13 95 views
1

我正在运行sql查询以将列中最大的值返回给程序。从列中选择最大数量不返回最大值

SQL查询我运行是..

select MAX([Line No]) from table 

我使用SQL Server 2008

该表有3行, '行号' 有50值,90,100

我预计将返回的最大值是100, 但即时获得90.为什么?

编辑:

string LineNo = "0"; 

    //LineNo 
    string SQLlineno = "select MAX(CAST([Line No] As Int)) from Saved_Order_Import where [order no] = '" 
         + ordernumber + "'"; 
    SqlCommand myCommandlineno = new SqlCommand(SQLlineno, myConnection); 
    SqlDataReader readerline; 
    try 
    { 
     readerline = myCommandlineno.ExecuteReader(); 
     if (readerline.HasRows) 
     { 
      while (readerline.Read()) 
      { 
       try 
       { 
        if (readerline.GetString(0) != null) 
        { 
         LineNo = (readerline.GetString(0) + 10).ToString(); 
        } 
       } 
       catch (Exception ex) { return "{\"error\":\"line : " + ex.ToString() + "\"}"; } 
      } 
     } 
     readerline.Close(); 
    } 
    catch (Exception ex) 
    { 
     // return "{\"error\":\"Other One11" + ex.ToString() + "\"}"; 
    } 
+0

看到我的'ExecuteScalar'更新 – 2012-01-13 16:46:11

回答

6

你列很可能不是一个数字类型,但字符串类型(CHAR,NCHAR,VARCHAR,NVARCHAR)。因此,它按字母顺序排序,并且9之后出现1.

最简单的事情就是更改为该列的正确数据类型。如果你不能这样做,则需要在MAX内回退到正确的类型。

例如,

select max(cast ([Line No] as int)) 
from table 

如果在该列无法转换为要过滤掉一些一些值,你可以这样做:

select max(cast ([Line No] as int)) 
from table 
where isnumeric([Line No]) = 1 

或者,只显示非数字值,所以你可以修复它们,你可以这样做:

select * 
from table 
where isnumeric([Line No]) = 0 

对于更健壮的整数检测,s ee值这篇文章:Can I Convert This String to an Integer?

+0

啊是的,它是字符串类型!任何关于我可以用什么查询的建议呢?我不能改变列的数据类型 – Beginner 2012-01-13 16:20:39

+0

'select MAX(CAST([Line No] as int))from table' should be the trick。 – 2012-01-13 16:22:40

+0

@Beginner看到我上面的更新。 – RedFilter 2012-01-13 16:22:41

1
select MAX(cast([Line No] as int)) from table 

UPADTE: 请拨打SqlCommandGetSringExecuteScalar

int max = (int)myCommandlineno.ExecuteScalar(); 
+0

谢谢,但不在代码中工作 – Beginner 2012-01-13 16:32:03

+0

System.Data.SqlTypes.SqlNullValueException:数据为空。此方法或属性无法在空值上调用 – Beginner 2012-01-13 16:42:37

+0

@Beginner错误消息是什么?在代码恐怕 – 2012-01-13 16:42:47

0

作为RedFilter的回答,它可能是一个不同的类型。列值转换为数字类型,然后应用最多的功能

select MAX(CAST(LineNo AS INT) from table 
+0

不工作。使用'GetInt32'获取值。另外,要检查空值,应该使用'IsDbNull'方法,而不是将值与'null'进行比较。数据库驱动程序从不返回“null”值,它返回“DbNull”值。 – Beginner 2012-01-13 16:31:55

0

要想从文本数据的数字maximium,你要投的价值是:如果你有其他的字母数字值

select max(cast([Line No] as int)) from table 
+0

不工作的代码 – Beginner 2012-01-13 16:31:47

+0

这就是怎么一回事,因为这是一个整数,现在,不是字符串 – Guffa 2012-01-13 17:09:41

0

在列不能转换成int,并要忽略他们,但你还是要一个字符串返回代码,你可以做这样的事情:

select cast(max(cast(LineNo AS int) as varchar(10)) 
from table 
where isnumeric([LineNo] = 1) 

Howeve r,如果该列旨在保存整数,我建议您安排一些开发时间来更改列类型并将任何非整数迁移到可接受的值。如果你不使用正确的数据类型,你真的会陷入麻烦。