How to return default value from SQL query

后端 未结 8 1879
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 13:25

Is there any easy way to return single scalar or default value if query doesn\'t return any row?

At this moment I have something like this code example:



        
相关标签:
8条回答
  • 2020-12-05 13:27

    You can drop the if statement using following construct but that doesn't necessarely mean it is better.

    SELECT Name FROM Users WHERE Id = @UserId UNION ALL 
    SELECT 'John Doe' WHERE NOT EXISTS (SELECT Name FROM Users WHERE  Id = @UserId)
    
    0 讨论(0)
  • 2020-12-05 13:32
    Try this 
    `SELECT IFNULL(Name,'John Doe') FROM Users WHERE Id = @UserId)`
    
    0 讨论(0)
  • 2020-12-05 13:36

    I would suggest that the best way to do is that first declare @name . Then set this value based on user id and then if @name is null show default name otherwise show name... That method would be as efficient as any other method and will be more readable.for other methods any other user to have think a lot to know what is going on unless there is nice comment.

    declare @userid int
    set @userid = 1
    select isnull(
                   (select name from users where id = @userid),
                   'John Doe'
                   )
     go
    --My preffered would be this one..
    declare @name varchar(20),@userid int
    set @userid = 1
    select  @name =  name from users where id = @userid
    select isnull(@name,'John Doe') 
    
    0 讨论(0)
  • 2020-12-05 13:40

    If the query is supposed to return at most one row, use a union with the default value then a limit:

    SELECT * FROM 
     (
      SELECT Name FROM Users WHERE Id = @UserId`
      UNION
      SELECT 'John Doe' AS Name --Default value
     ) AS subquery
    LIMIT 1
    

    Both the query and default can have as many columns as you wish, and you do not need to guarantee they are not null.

    0 讨论(0)
  • 2020-12-05 13:46

    I suppose you could use @@ROWCOUNT to see if any will be returned.

    SELECT Name FROM Users WHERE Id = @UserId  
    if(@@ROWCOUNT = 0)
      SELECT 'John Doe'
    

    You could also use a variable if you're expecting one row.

    declare @name varchar(100)
    set @name = (select top 1 name from users where id = @userId)
    if(@name is null) set @name = 'John Doe'
    select @name
    
    0 讨论(0)
  • 2020-12-05 13:47

    Assuming the name is not nullable and that Id is unique so can match at most one row.

     SELECT 
        ISNULL(MAX(Name),'John Doe')
     FROM 
        Users 
     WHERE 
        Id = @UserId  
    
    0 讨论(0)
提交回复
热议问题