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

时间:2017-06-29 07:33:48

标签: sql sql-server

我现在正在使用Microsoft SQL,我的代码是:

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

我希望当[avail]存在时,返回[avail]的值,如果不存在,则返回0或“Not Found”

谢谢!

4 个答案:

答案 0 :(得分:3)

您可以使用此

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

答案 1 :(得分:0)

您可以通过两种方式完成:

使用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]

或将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]

答案 2 :(得分:0)

尝试使用COALESCE。它从第一个具有非空值的参数中选择数据。如果avail不为null,则返回[avale],否则返回“Not Found”

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

您可以在https://docs.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql

中阅读有关COALESCE的内容

答案 3 :(得分:-1)

如果你想要它的前1或删除顶部命令

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