Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a value if no rows are found in Microsoft tSQL

Tags:

tsql

Using a Microsoft version of SQL, here's my simple query. If I query a record that doesn't exist then I will get nothing returned. I'd prefer that false (0) is returned in that scenario. Looking for the simplest method to account for no records.

SELECT  CASE             WHEN S.Id IS NOT NULL AND S.Status = 1 AND (S.WebUserId = @WebUserId OR S.AllowUploads = 1) THEN 1             ELSE 0         END AS [Value]          FROM Sites S          WHERE S.Id = @SiteId 
like image 647
Matt Avatar asked Apr 21 '10 02:04

Matt


People also ask

How can you tell if a select returned no rows?

You can use @@ROWCOUNT. For e.g. You will get 0 if first statement will not return any rows. You can also use if statement to check that just after first statement.

Can a SQL query return a value?

The RETURN statement is used to unconditionally and immediately end an SQL procedure by returning the flow of control to the caller of the stored procedure. When the RETURN statement runs, it must return an integer value.


1 Answers

This is similar to Adam Robinson's, but uses ISNULL instead of COUNT.

SELECT ISNULL( (SELECT 1 FROM Sites S WHERE S.Id = @SiteId and S.Status = 1 AND        (S.WebUserId = @WebUserId OR S.AllowUploads = 1)), 0) 

If the inner query has a matching row, then 1 is returned. The outer query (with ISNULL) then returns this value of 1. If the inner query has no matching row, then it doesn't return anything. The outer query treats this like a NULL, and so the ISNULL ends up returning 0.

like image 104
Moe Sisko Avatar answered Oct 01 '22 23:10

Moe Sisko