[英]Returning 1 or 0 instead of value or null in T-SQL
In my SELECT
statement, I join two tables.在我的
SELECT
语句中,我连接了两个表。 It's possible that there's no corresponding value in Table2
in which case, my SELECT
statement should return NULL
for that column.在
Table2
中可能没有相应的值,在这种情况下,我的SELECT
语句应该为该列返回NULL
。 What I want to do is that instead of returning the actual value coming from Table2
I want to return a 1.我想要做的是,不是返回来自
Table2
的实际值,而是返回 1。
I thought I could use ISNULL
for this but that function is designed to return the actual value if one exists.我以为我可以为此使用
ISNULL
但该函数旨在返回实际值(如果存在)。
This is what my SELECT
statement looks like:这是我的
SELECT
语句的样子:
SELECT a.Id, ISNULL(b.PersonId, 0)
FROM Table1 AS a
LEFT OUTER JOIN Table2 AS b ON a.Id = b.Id
Here the PersonId
column is of UNIQUEIDENTIFIER
type and I don't want to return either a Guid
or a 0. Instead, I'd like to return a 1 or a 0.这里
PersonId
列是UNIQUEIDENTIFIER
类型,我不想返回Guid
或 0。相反,我想返回 1 或 0。
How can I handle this scenario?我该如何处理这种情况?
I think you're looking for a CASE EXPRESSION
here.我认为您正在寻找
CASE EXPRESSION
在这里。
SELECT a.Id, CASE WHEN b.PersonId IS NOT NULL THEN 1 ELSE 0 END
FROM Table1 AS a
LEFT OUTER JOIN Table2 AS b ON a.Id = b.Id
As well as @DaleK's excellent answer, another option is using EXISTS
除了@DaleK 的出色回答,另一种选择是使用
EXISTS
SELECT
a.Id,
CASE WHEN EXISTS (SELECT 1
FROM Table2 AS b
WHERE a.Id = b.Id)
THEN 1 ELSE 0 END
FROM Table1 AS a
Note that the semantic is different here, as it is a semi-join: the rows are not duplicated if there are multiple matches in Table2
需要注意的是语义不同,这里,因为它是一个半连接:行不被复制,如果有多个匹配
Table2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.