問題描述
我問了一個關于 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 的奇怪行為的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!