How to return default value from SQL query

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

提交回复
热议问题