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:
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.
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