C# ExecuteScalar() null COUNT 与 SELECT

C# ExecuteScalar() null COUNT vs SELECT

我注意到一些奇怪的行为,希望其中一位专家能够解释其中的区别。我的 UI 要求图像在呈现给用户执行任务之前是唯一的。我将校验和存储在数据库中并查询那些唯一值。我注意到我的逻辑 'flips' 取决于我是否使用标准 SELECT 查询与 SELECT COUNT。我已将它隔离到这行代码,但我不明白为什么。

SELECT 记录 FROM table WHERE checksum = something

//This code works correctly (true / false)
Object result = command.ExecuteScalar();
bool checksumExists = (result == null ? false : true);

//Returns TRUE no matter what
Object result = command.ExecuteScalar();
bool checksumExists = (result == DBNull.value ? false : true);

我更改为以下 SQL 以针对大型 table 和我的逻辑 'flipped'

进行性能

SELECT COUNT (record) FROM table WHERE checksum = something

//Now this code always returns TRUE
Object result = command.ExecuteScalar();
bool checksumExists = (result == null ? false : true);

//Now this is the solution
Object result = command.ExecuteScalar();
bool checksumExists = (Convert.ToInt32(result) < 1 ? false : true);

COUNT 语句是否意味着它总是 return 一个数字,即使没有找到任何行?

Does the COUNT statement mean that it will always return a number, even if no rows are found?

是的。零是一个数字。和

SELECT COUNT(someCol) c FROM table WHERE 1=2

将始终 return 单行单列结果集,例如:

c
-----------
0

(1 row affected)

COUNT 不是检查是否有任何行符合条件的最有效方法,因为它会继续对第一行以外的行进行计数。

您可以使用 EXISTS 或 TOP 1 生成查询,该查询将在找到一行后停止。乙

   select someMatchesExist = case when exists(select * from table where ...) then 1 else 0 end

select top (1) 1 as someMatchesExist  from table where ...