How to return default value from SQL query

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

    I suppose you could use @@ROWCOUNT to see if any will be returned.

    SELECT Name FROM Users WHERE Id = @UserId  
    if(@@ROWCOUNT = 0)
      SELECT 'John Doe'
    

    You could also use a variable if you're expecting one row.

    declare @name varchar(100)
    set @name = (select top 1 name from users where id = @userId)
    if(@name is null) set @name = 'John Doe'
    select @name
    

提交回复
热议问题