简体   繁体   English

如果没有找到记录,SQL select 返回 0,否则返回值

[英]SQL select return 0 if no records found, else return value

I am now using Microsoft SQL, my code is:我现在使用 Microsoft SQL,我的代码是:

   SELECT TOP 1 
   [avail]
   FROM [table1]
   where [name] = 'abc'
   order by [datetime] desc

I hope when [avail] exists, return the value of [avail], if not exists, return 0 or "Not Found"我希望当 [avail] 存在时,返回 [avail] 的值,如果不存在,则返回 0 或“Not Found”

Thanks!谢谢!

You can use this你可以用这个

SELECT ISNULL(( SELECT TOP 1 
   [avail]
   FROM [table1]
   where [name] = 'abc'
   order by [datetime] desc), 0) AS [avail]

You can do in two ways:您可以通过两种方式进行:

Use IF EXISTS way:使用IF EXISTS方式:

IF EXISTS (SELECT TOP 1 [avail] FROM [table1] WHERE [name] = 'abc' ORDER BY [datetime] DESC)
    SELECT TOP 1 [avail] FROM [table1] WHERE [name] = 'abc' ORDER BY [datetime] DESC
ELSE 
    SELECT 0 AS [avail]

or store the avail value into a variable and process, the only risk in this way is if the top 1 avail is returns empty value, then you will get the result as zero.或者将avail值存储到一个变量中并进行处理,这种方式的唯一风险是如果top 1 avail返回空值,那么您将得到的结果为零。

DECLARE @Avail AS VARCHAR(100) = ''; -- varchar of the `avail` data size

SELECT TOP 1 @Avail = [avail] FROM [table1] WHERE [name] = 'abc' ORDER BY [datetime] DESC;

IF @Avail = ''
    SELECT 0 AS [avail]
ELSE 
    SELECT @Avail AS [avail]

Try to use COALESCE.尝试使用 COALESCE。 It selects the data from the first argument that has a nonnull value.它从具有非空值的第一个参数中选择数据。 If avail is not null, return [avale], otherwise return "Not Found"如果avail 不为空,返回[avale],否则返回“Not Found”

SELECT COALESCE(avail, 'Not Found')
FROM table1
WHERE name = 'abc'
ORDER BY datetime desc

You can read about COALESCE in https://docs.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql您可以在https://docs.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql 中阅读有关 COALESCE 的信息

If its top 1 you want or remove top command如果它是您想要的前 1 名或删除 top 命令

 SELECT TOP 1 
   isnull([avail],'0')
   FROM [table1]
   where [name] = 'abc'
   order by [datetime] desc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM