簡體   English   中英

在SQL數據庫中查找最大的數字,如果不可用,則返回“ 0”

[英]Find the highest number in SQL database, if unavailable return '0'

目前,我正在為ASP.NET C#Web應用程序提供一種方法來檢索SQL數據庫列中的最高編號。 現在,我設法產生以下代碼。

commTagNo = new SqlCommand("SELECT MAX(ComponentTagEntry) FROM dbo.HullDataSheet", connHull);

connHull.Open();
int newTagNo = (int)commTagNo.ExecuteScalar();
connHull.Close();

newTagNo = newTagNo + 1;

其中connHull是以上代碼行的SqlConnection

僅當數據庫已經具有至少一行數據時,以上代碼才能檢索ComponentTagEntry列中的最高編號。

如果數據庫為空,則由於沒有數據可以執行,因此它將返回“指定的轉換無效” .ExecuteScalar()

我需要的是,當數據庫為空時,代碼檢索最高的數字為“ 0”。

我知道我必須使用if then語句修改上面的代碼,但是我不知道必須與true / false語句進行比較的值。

任何幫助都非常感謝。

coalesce是必經之路:

select coalesce(max(ComponentTagEntry)) from ...

例如:

create table dbo.HullDataSheet (ComponentTagEntry int);

select coalesce(max(ComponentTagEntry), 0) from HullDataSheet

SQL Server parse and compile time: 
   CPU time = 0 ms, elapsed time = 0 ms.

-----------
0

(1 row(s) affected)

Table 'HullDataSheet'. Scan count 1, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.
SQL Server parse and compile time: 
   CPU time = 0 ms, elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.

ISNULL運算符應該有所幫助。

commTagNo = new SqlCommand("SELECT ISNULL(MAX(ComponentTagEntry), 0) FROM dbo.HullDataSheet", connHull);

我建議

int newTagNo = 0;
object testMe = commTagNo.ExecuteScalar();
if (testMe != null) { newTagNo = (int)testMe; }

試試這個查詢。 兼容SQL Server和Mysql:

select 
    case 
       when MAX(ComponentTagEntry) IS NULL 
          then 0 
          else MAX(ComponentTagEntry) 
    end 
from 
    dbo.HullDataSheet

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM