How to return default value from SQL query

后端 未结 8 1889
佛祖请我去吃肉
佛祖请我去吃肉 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:50

    Try ISNULL or COALESCE:

    SELECT ISNULL((SELECT TOP 1 Name FROM Users WHERE Id = @UserId), 'John Doe')
    

    The inner select will return nothing if no user exist with this id, the isnull will solve this case.

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

    Try isnull

    SELECT IsNULL(Name, 'John Doe')  FROM Users WHERE Id = @UserId
    

    Edit:

    drop table users
    go
    create table users
    (id int,name varchar(20))
    go
    insert into users select 1,'1'
     go
    declare @userid int
    set @userid = 1
    select isnull(username.username, 'John Doe')
    from (select @userid as userid) userid
    outer apply (SELECT  name as username FROM Users WHERE Id = userid.userid ) username
    --outer apply (SELECT  name as username FROM Users WHERE Id = @userid ) username
    
    0 讨论(0)
提交回复
热议问题