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:
IF (EXISTS (SELECT * FROM Users WHERE Id = @UserId)) SELECT Name FROM Users WHERE Id = @UserId ELSE --default value SELECT 'John Doe'
How to do that in better way without using IF-ELSE?
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.
The DEFAULT Constraint is used to fill a column with a default and fixed value. The value will be added to all new records when no other value is provided. Dropping the default constraint will not affect the current data in the table, it will only apply to new rows.
The default value is used for the column's value when one is not specified (for example, when you insert a row into the table without specifying a value for the column). You can add a default constraint either when creating a table or after the table already exists.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With