简体   繁体   English

在SQL数据库中查找最大的数字,如果不可用,则返回“ 0”

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

Currently I am working on producing a way for ASP.NET C# web app to retrieve the highest number in a column in SQL database. 目前,我正在为ASP.NET C#Web应用程序提供一种方法来检索SQL数据库列中的最高编号。 Right now, I manage to produce the following line of code. 现在,我设法产生以下代码。

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

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

newTagNo = newTagNo + 1;

where connHull is the SqlConnection for above line of codes. 其中connHull是以上代码行的SqlConnection

The above code can retrieve the highest number in column ComponentTagEntry if and only if the database already have a minimum one row of data. 仅当数据库已经具有至少一行数据时,以上代码才能检索ComponentTagEntry列中的最高编号。

If the database is empty, it will return 'Specified cast is invalid' since there are no data to do .ExecuteScalar() . 如果数据库为空,则由于没有数据可以执行,因此它将返回“指定的转换无效” .ExecuteScalar()

What I need is, when the database is empty, for the code to retrieve the highest number as '0'. 我需要的是,当数据库为空时,代码检索最高的数字为“ 0”。

I know that I have to modify the above code with if then statement but I don't know the value that I must compare to the true/false statement. 我知道我必须使用if then语句修改上面的代码,但是我不知道必须与true / false语句进行比较的值。

Any help is very appreciated. 任何帮助都非常感谢。

coalesce is the way to go: coalesce是必经之路:

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

For example: 例如:

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);

I'd suggest 我建议

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

Try this query. 试试这个查询。 Compatible in both SQL Server & Mysql: 兼容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