SQL Server 字符串与 Null 的连接
我正在跨字段创建一个计算列,其中一些字段可能为空。
问题是,如果这些字段中的任何一个为空,则整个计算列将为空。我从 Microsoft 文档中了解到,这是预期的,可以通过设置 SET CONCAT_NULL_YIELDS_NULL 关闭。但是,我不想更改此默认行为,因为我不知道它对 SQL Server 其他部分的影响。
有没有办法让我只检查列是否为空,并且仅在计算列公式不为空时将其内容附加到计算列公式中?
I am creating a computed column across fields of which some are potentially null.
The problem is that if any of those fields is null, the entire computed column will be null. I understand from the Microsoft documentation that this is expected and can be turned off via the setting SET CONCAT_NULL_YIELDS_NULL. However, there I don't want to change this default behavior because I don't know its implications on other parts of SQL Server.
Is there a way for me to just check if a column is null and only append its contents within the computed column formula if its not null?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
您可以使用
ISNULL(....)
如果列/表达式的值确实为 NULL,则将使用指定的第二个值(此处:空字符串)。
You can use
ISNULL(....)
If the value of the column/expression is indeed NULL, then the second value specified (here: empty string) will be used instead.
从 SQL Server 2012 开始,使用
CONCAT
一切都变得更加容易 函数。它将
NULL
视为空字符串From SQL Server 2012 this is all much easier with the
CONCAT
function.It treats
NULL
as empty string使用合并。使用
COALESCE(your_column, '')
而不是your_column
。这将返回空字符串而不是 NULL。Use COALESCE. Instead of
your_column
useCOALESCE(your_column, '')
. This will return the empty string instead of NULL.您还可以使用 CASE - 我下面的代码检查空值和空字符串,并仅在有值跟随时添加分隔符:
You can also use CASE - my code below checks for both null values and empty strings, and adds a seperator only if there is a value to follow:
使用
空值并将其串联到字符串中不会导致空值。
请注意,这是一个已弃用的选项,请避免使用。
请参阅 文档了解更多详细信息。
Use
and concatenation of null values to a string will not result in null.
Please note that this is a deprecated option, avoid using.
See the documentation for more details.
我只是想贡献一下,如果有人寻求在字符串之间添加分隔符的帮助,具体取决于字段是否为 NULL 。
因此,在从不同字段创建一行地址的示例中
在我的例子中,我有以下计算列似乎按我想要的方式工作:
希望对某人有帮助!
I just wanted to contribute this should someone be looking for help with adding separators between the strings, depending on whether a field is NULL or not.
So in the example of creating a one line address from separate fields
in my case, I have the following Calculated Column which seems to be working as I want it:
Hope that helps someone!
ISNULL(ColumnName, '')
ISNULL(ColumnName, '')
我也为此遇到了很多麻烦。使用上面的案例无法让它工作,但这对我来说很有效:
替换纠正了由于连接单个空格而导致的双空格,并且它们之间没有任何内容。 r/ltrim 删除末尾的任何空格。
I had a lot of trouble with this too. Couldn't get it working using the case examples above, but this does the job for me:
Replace corrects the double spaces caused by concatenating single spaces with nothing between them. r/ltrim gets rid of any spaces at the ends.
在 Sql Server 中:
代码隐藏:
In Sql Server:
Code Behind:
此示例将帮助您在创建插入语句时处理各种类型
This example will help you to handle various types while creating insert statements