Select statement to return constant when no record

2019-09-11 04:23发布

I am have a table with data and now i need to return zero in select statement if there is no records in table for example. I need to use it in Stored Procedure.

-- If no records exists in below select statement
SELECT ID,Text,Date FROM tblData WHERE ID = 12

IF (@@ROWCOUNT = 0)
BEGIN
    SELECT -5 AS ID
END

Output:

ID  Text  Date


ID
-5

Expected output

ID
-5

4条回答
ら.Afraid
2楼-- · 2019-09-11 05:12

If you want to return 1 row even when there is no match, you can use aggregation:

SELECT (CASE WHEN COUNT(*) = 0 THEN -5 ELSE MAX(ID) END) as ID
FROM tblData
WHERE ID = 12;
查看更多
Emotional °昔
3楼-- · 2019-09-11 05:16

For a single scalar value you could use something like;

SELECT ISNULL((SELECT ID FROM tblData WHERE ID = 12), 0) as ID

Rhys

查看更多
地球回转人心会变
4楼-- · 2019-09-11 05:17

I always use an Exists statment.

if exists(SELECT ID FROM tblData WHERE ID = 12)
    select 0 as RowsExist
else
    select 1 as RowsExist
查看更多
Lonely孤独者°
5楼-- · 2019-09-11 05:18
SELECT (CASE WHEN Ta.ID IS NULL THEN TBL.ID 
ELSE Ta.ID END) AS ID,Ta.Text,Ta.Date
FROM (VALUES(-5)) AS TBL(ID)
LEFT JOIN
(
   SELECT ID,Text,Date FROM tblData WHERE ID = 12
)
AS Ta ON Ta.ID = Ta.ID
查看更多
登录 后发表回答