简体   繁体   English

TSQL CASE,当id.id为null时,则为” else'@'结束

[英]TSQL CASE WHEN id.id null then '' else '@' end

In my select, I'm using a statement like this to add a second cell, if it is not null, and to zero out the cell if it is null. 在我的选择中,我使用这样的语句添加第二个单元格(如果它不为null),以及将该单元格清零(如果它为null)。

Child.Tag + '@' + ISNULL(CONVERT(varchar(50),parent.Tag),'') as 'Location'

This returns a location of F123@A123 if there is a parent location. 如果存在父位置,则返回F123 @ A123的位置。 However if there isn't a parent location, it will return F123@, where I would like it to only return F123. 但是,如果没有父位置,它将返回F123 @,我希望它仅返回F123。

I have adjusted the select to this: 我已经将选择调整为:

Child.Tag + CASE Parent.Tag when null then '' else '@' end

However this still returns F123@ if the parent location is null. 但是,如果父位置为null,则仍返回F123 @。

Does anyone know of a way to have it stop returning the '@', and if anyone has an explanation as to why my CASE statement isn't working that would be greatly appreciated as well. 有谁知道让它停止返回“ @”的方法,并且如果有人对我的CASE语句为什么不起作用的解释,也将不胜感激。

Thank you. 谢谢。

(Other info: I am on SSMS 2008) (其他信息:我正在使用SSMS 2008)

I think you want this: 我想你想要这个:

Child.Tag + COALECE('@' + Parent.Tag, '')

This adds the '@' only when there is a value for Parent.Tag . 仅当存在Parent.Tag的值时,才添加'@'

The documentation for the simple case is: 简单case文档是:

  • Evaluates input_expression, and then in the order specified, evaluates input_expression = when_expression for each WHEN clause. 评估input_expression,然后按照指定的顺序为每个WHEN子句评估input_expression = when_expression。

NULL fails the equality test. NULL未通过相等性测试。 This is subtle, but the COALESCE() form is easier to read and write anyway. 这很微妙,但是无论如何, COALESCE()形式更易于读写。

As Gordon notes, CASE Parent.Tag when null never evaluates as true, even when Parent.Tag is NULL - however, CASE when Parent.Tag is null will evaluate as true when Parent.Tag is NULL. 戈登指出, CASE Parent.Tag when null从不评估为真,即使Parent.Tag为空-但是, CASE when Parent.Tag is null时, 评估为真Parent.Tag为NULL。

So you could have rewritten your existing expression from the CASE expression WHEN value ... form, to the CASE WHEN expression-is-true ... form, like so: 因此,您可以将现有的表达式从CASE 表达式 WHEN ...形式重写为CASE WHEN 表达式 -is -true ...形式,如下所示:

Child.Tag + CASE when Parent.Tag is null then '' else '@' end + ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM