SQL select return 0 if no records found, else return value

后端 未结 4 625
再見小時候
再見小時候 2021-01-24 18:02

I am now using Microsoft SQL, my code is:

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

I

相关标签:
4条回答
  • 2021-01-24 18:40

    You can do in two ways:

    Use IF EXISTS way:

    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.

    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]
    
    0 讨论(0)
  • 2021-01-24 18:43

    You can use this

    SELECT ISNULL(( SELECT TOP 1 
       [avail]
       FROM [table1]
       where [name] = 'abc'
       order by [datetime] desc), 0) AS [avail]
    
    0 讨论(0)
  • 2021-01-24 18:57

    If its top 1 you want or remove top command

     SELECT TOP 1 
       isnull([avail],'0')
       FROM [table1]
       where [name] = 'abc'
       order by [datetime] desc
    
    0 讨论(0)
  • 2021-01-24 18:59

    Try to use 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"

    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

    0 讨论(0)
提交回复
热议问题