How to return default value from SQL query

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

提交回复
热议问题