paparazzo
paparazzo

Reputation: 45096

Return a value if no rows match

The [authorityID] (TinyInt) column will never be null.

What I want is to return a 15 if there are no rows. With the query below I get nothing if there are no rows:

select top 1 isnull([authorityID],15) 
from [docAuthority] with (nolock) 
where [grpID] = 0 and [sID] = 42

Upvotes: 2

Views: 299

Answers (2)

Ricardo C
Ricardo C

Reputation: 2244

SELECT  authorityId = isnull(( SELECT   [authorityID]
                               FROM     [docAuthority] WITH ( NOLOCK )
                               WHERE    [grpID] = 0
                                        AND [sID] = 42
                             ), 15)

Upvotes: 3

Mureinik
Mureinik

Reputation: 310983

As you noted, if the query returns no rows, there's nothing to apply the isnull on. One dirty trick is to use union all and (ab)use the top construct:

SELECT TOP 1 authorityID
FROM   (SELECT authorityID
        FROM   [docAuthority] WITH (nolock) 
        WHERE  [grpID] = 0 AND [sID] = 42
        UNION ALL
        SELECT 15) t

Upvotes: 1

Related Questions