SQL Case 语句语法

发布于 2024-07-21 11:08:31 字数 225 浏览 3 评论 0原文

我正在尝试编写一个选择语句,该语句将选择多个字段,包括电子邮件字段。 此表中有 3 个可用的电子邮件字段,有时可能包含空值。 我想看3个领域; [电子邮件地址1]、[电子邮件地址2]、[电子邮件地址3]基本上我想做的是如果[电子邮件地址3]为空那么我想要[电子邮件地址2]中的值,如果电子邮件地址2为空比我想要的值在 [email address1] 中,

我似乎无法正确理解语法,并且不太确定我做错了什么。

I am trying to write a select statement that will select a number of fields including an email field. There are 3 email fields available in this table which can sometimes contains null values. I wan to look at 3 fields; [email address1], [email address2], [email address3] and basically what I want to do is if [email address3] is null then I want the value in [email address2], If email address2 is null than I want the value in [email address1]

I can't seem to get the Syntax right and am not too sure what I'm doing wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蘸点软妹酱 2024-07-28 11:08:31

您需要的是 COALESCE(...) 函数

SELECT COALESCE(t.Email3, t.Email2, t.Email1) FROM MyTable t

What you need is COALESCE(...) function:

SELECT COALESCE(t.Email3, t.Email2, t.Email1) FROM MyTable t
尝蛊 2024-07-28 11:08:31

不需要 CASE,您还可以使用 COALESCE (“返回其参数中的第一个非空表达式”):

SELECT COALESCE(Email3, Email2, Email1) ...

No need for CASE, you can also use COALESCE ("Returns the first nonnull expression among its arguments"):

SELECT COALESCE(Email3, Email2, Email1) ...
咿呀咿呀哟 2024-07-28 11:08:31

请参阅有关 COALESCE 的其他答案,但如果您确实想要一个 CASE 结构,那么应该这样做:

CASE
  WHEN email3 IS NOT NULL THEN email3
  WHEN email2 IS NOT NULL THEN email2
  WHEN email1 IS NOT NULL THEN email1
  ELSE ''
END

我添加了 else 子句以防止从整个事情中返回 Null,但如果这就是您想要发生的情况当所有三个都为 Null 时,您可以使用:

CASE
  WHEN email3 IS NOT NULL THEN email3
  WHEN email2 IS NOT NULL THEN email2
  ELSE email1
END

请注意,SQL Server CASE 函数不会删除案例 - 一旦它匹配一个,就这样。 不需要“休息”。

See other answers about COALESCE, but if you really want a CASE structure, this should do it:

CASE
  WHEN email3 IS NOT NULL THEN email3
  WHEN email2 IS NOT NULL THEN email2
  WHEN email1 IS NOT NULL THEN email1
  ELSE ''
END

I added the else clause to prevent returning a Null from the whole thing, but if that's what you want to happen when all three are Null you can use:

CASE
  WHEN email3 IS NOT NULL THEN email3
  WHEN email2 IS NOT NULL THEN email2
  ELSE email1
END

Note that the SQL Server CASE function does not drop through cases--once it matches one, that's it. No need for a "break".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文