Return a Value If No Record Is Found

Return a value if no rows are found in Microsoft tSQL


SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END AS [Value]

FROM Sites S

WHERE S.Id = @SiteId and S.Status = 1 AND
(S.WebUserId = @WebUserId OR S.AllowUploads = 1)

SQL query - Return 0 for the column if no record found

Try below query:

SELECT A.Customer, ISNULL(B.Address, 0), 
ISNULL(B.[Number of lines],0), ISNULL(B.Date, '30-05-2022') Date
FROM
(
SELECT DISTINCT Customer
FROM table_name
) A
LEFT JOIN table_name B
ON A.Customer = B.Customer
AND B.Date = '30-5-2022'

This will output all the customers present in the table. You can filter the customers with WHERE clause in the end of the above query based on your requirement.

dbfiddle Link

SQL select return 0 if no records found, else return value

You can use this

SELECT ISNULL(( SELECT TOP 1 
[avail]
FROM [table1]
where [name] = 'abc'
order by [datetime] desc), 0) AS [avail]


Related Topics



Leave a reply



Submit