2012-01-13 147 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,如果該列旨在保存整數,我建議您安排一些開發時間來更改列類型並將任何非整數遷移到可接受的值。如果你不使用正確的數據類型,你真的會陷入麻煩。