在 SQL Server 的 OPENXML 函数中将空元素视为 null
我有以下(高度简化的)XML 文档,我正在使用 OPENXML 函数将其读入数据库:
<root>
<row>
<bar>123</bar>
</row>
<row>
<bar>0</bar>
</row>
<row>
<bar></bar>
</row>
</root>
我像这样导入到数据库中:
insert into [Foo]
([bar])
select
ds.[bar]
from openxml(@xmlHandle, 'root/row', 2)
with ([bar] int) ds
问题是 OPENXML 将 int 数据类型的空字段转换为零,所以这插入到我的表中:
bar
----
123
0
0
我想要插入到表中的是:
bar
----
123
0
NULL
如何让 OPENXML 函数将空字段视为 NULL,并且默认情况下不将其转换为零?
I have the following (highly simplified) XML document that I am reading into my database using the OPENXML function:
<root>
<row>
<bar>123</bar>
</row>
<row>
<bar>0</bar>
</row>
<row>
<bar></bar>
</row>
</root>
I am importing in into the database like so:
insert into [Foo]
([bar])
select
ds.[bar]
from openxml(@xmlHandle, 'root/row', 2)
with ([bar] int) ds
The problem is that OPENXML converts empty fields with the int data type to zero, so this gets inserted into my table:
bar
----
123
0
0
What I want inserted into my table is:
bar
----
123
0
NULL
How do I get the OPENXML function to treat empty fields as NULL and not convert it to zero by default?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于没有人有任何想法,这就是我“解决”它的方法,尽管对我来说这似乎是一种黑客攻击:
Since no one has any ideas, here is how I am "solving" it, though it seems like a hack to me:
刚刚遇到了类似的问题,并使用 SQL 中的 NULLIF 函数解决了它。
MSDN 上的 NULLIF
我相信你也会忽略它:)
摆脱由
CASE...END
语句造成的混乱。希望有帮助!
Just faced a similar problem and solved it with the
NULLIF
function in SQL.NULLIF on MSDN
I am sure you would have overlooked it as well :)
Gets rid of the clutter created by the
CASE... END
statements.Hope it helps!
不确定您的 xml 有多“高度简化”,但如果您有一个指定 null 的属性,您也可以执行类似于答案的操作 此处;基本上:
这个场景对我有用
Not sure how 'highly simplified' your xml is, but if you have an attribute that specifies null, you can also do something similar to the answer here; basically:
This scenario has worked for me
我最初使用 NULLIF 作为已经建议的,但我在WITH模式中找到了另一个选项:
我正在查看数百列和数千行,所以大小不错,但不是很大。我发现性能与 this 或 NULLIF 基本相同,但我喜欢将定义保留在 WITH 子句中,以便 SELECT 可以保持干净(因为我倾向于在那里发生很多其他事情)。
青年MMV
I originally used NULLIF as already suggested, but I found another option in the WITH schema:
I'm looking at hundreds of columns and thousands of rows, so a decent size but not huge. I've found performance to be basically the same with this or NULLIF, but I like keeping the definition in the WITH clause so the SELECT can stay clean (because I tend to have plenty of other stuff happening there).
YMMV
如果完全省略 Bar 元素,您将得到所需的结果。
然后
结果是
If you omit the Bar element entirely, you will get your desired result.
and then
results in