如何控制sql server中null int字段到varchar的转换?

发布于 2024-12-06 07:50:02 字数 501 浏览 0 评论 0 原文

首先我想知道CAST如何与NULL字段一起使用以及当值为NULL时它的行为如何?

例如,在表达式中:

(CAST(INT_FIELD as nvarchar(100))

如果值 INT_FIELDNULL 会发生什么?

原因是,当我尝试执行以下操作时:

SELECT (CAST(INT_FIELD as nvarchar(100)) + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;

即使 SOME_OTHER_FIELD 不为 null,我也得到 NULL。我猜它有某种逻辑 NULL + some = NULL 但我不确定。

我怎样才能控制这种行为?

First of all I would like to know how does CAST work with NULL fields and how does it behave when the value is NULL?

For example in the expression:

(CAST(INT_FIELD as nvarchar(100))

what happens if the value INT_FIELD is NULL?

The reason is that when I'm trying to do the following:

SELECT (CAST(INT_FIELD as nvarchar(100)) + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;

I'm getting NULL even though the SOME_OTHER_FIELD is not null. I'm guessing it has some kind of logic that NULL + something = NULL but I'm not sure.

How can I control this behavior?

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

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

发布评论

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

评论(4

三生路 2024-12-13 07:50:02

您需要使用 ISNULLCOALESCE,因为 NULL 之间的大多数行操作都会导致 NULLNULL 的 >CAST 返回 NULLNULL + 某些内容也是 NULL。在你的例子中,你应该这样做:

SELECT ISNULL(CAST(INT_FIELD as nvarchar(100)),'') + ' ' + ISNULL(SOME_OTHER_FIELD,'')
FROM SOME_TABLE;

当然,在我的例子中,如果两个字段都是NULL,它将返回''而不是'',但你明白了。

You need to use ISNULL or COALESCE, since most row operation between a NULL is gonna result in NULL. CAST of a NULL returns NULL and NULL + something is also NULL. In your example you should do something like this:

SELECT ISNULL(CAST(INT_FIELD as nvarchar(100)),'') + ' ' + ISNULL(SOME_OTHER_FIELD,'')
FROM SOME_TABLE;

Of course, in my example, if both fields are NULL it will return ' ' instead of '', but you get the idea.

忆离笙 2024-12-13 07:50:02

查看 COALESCE,您可以在其中找到第一个非空值,如果全部为空则返回 0,例如:

SELECT (CAST(COALESCE(INT_FIELD,0) as nvarchar(100)) + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;

Look into COALESCE, where you can find the first non-null and return 0 if all are null, e.g:

SELECT (CAST(COALESCE(INT_FIELD,0) as nvarchar(100)) + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;
甚是思念 2024-12-13 07:50:02

尝试使用COALESCE

SELECT COALESCE(CAST(INT_FIELD as nvarchar(100), '') + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;

Try using COALESCE

SELECT COALESCE(CAST(INT_FIELD as nvarchar(100), '') + ' ' + SOME_OTHER_FIELD FROM SOME_TABLE;
剩余の解释 2024-12-13 07:50:02

通常,NULL +(-,/,*, etc) something = NULL
您可以使用

SELECT ISNULL(CAST(INT_FIELD as nvarchar(100)),'') 
+ ' ' + ISNULL(SOME_OTHER_FIELD FROM SOME_TABLE,'')

或者SET CONCAT_NULL_YIELDS_NULL OFF更多详细信息)

Normally, NULL +(-,/,*, etc) something = NULL.
You can use

SELECT ISNULL(CAST(INT_FIELD as nvarchar(100)),'') 
+ ' ' + ISNULL(SOME_OTHER_FIELD FROM SOME_TABLE,'')

or you can SET CONCAT_NULL_YIELDS_NULL OFF (more details)

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