strange behavior of SQL Server when sum nodes#39;s values in XML(对 XML 中的节点值求和时 SQL Server 的奇怪行为)
问题描述
我问了一个关于 sum 节点值的问题:
I ask a question about sum node's values:
总结 sql server 2008 中的一些 xml 节点值
请考虑此代码:
Declare @xml xml
set @xml='<Parent ID="p">
<Child ID="1">1000000000</Child >
<Child ID="2">234650</Child >
<Child ID="3">0</Child >
</Parent >'
Select @xml.value('sum(/Parent[@ID="p"]/Child)','bigint') as Sum
如果你执行这个它会重新运行这个错误:
if you execute this it retrun this error:
Msg 8114, Level 16, State 5, Line 8将数据类型 nvarchar 转换为 bigint 时出错.
Msg 8114, Level 16, State 5, Line 8 Error converting data type nvarchar to bigint.
问题是它返回这个值:1.00023465E9
如果我以这种方式更改上述查询就可以了:
if I change the above query this way it being ok:
Declare @xml xml
set @xml='<Parent ID="p">
<Child ID="1">1000000000</Child >
<Child ID="2">234650</Child >
<Child ID="3">0</Child >
</Parent >'
Select @xml.value('sum(/Parent[@ID="p"]/Child)','float') as Sum
为什么 Sql Server 这样做?
Why Sql Server do this?
推荐答案
Sql Server 在将带有科学记数法的值从字符串转换为整数时出现问题,这在您运行 xpath 查询时会发生,但是,它可以做到这是 float.
Sql Server has a problem converting the value with scientific notation from a string to an integer, as would happen when you run your xpath query, however, it can do this for float.
您可以这样编写查询:
select @xml.value('sum(/Parent[@ID = "p"]/Child) cast as xs:long?', 'bigint')
这篇关于对 XML 中的节点值求和时 SQL Server 的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对 XML 中的节点值求和时 SQL Server 的奇怪行为
基础教程推荐
- 带有WHERE子句的LAG()函数 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
