strange behavior of SQL Server when sum nodes's values in XML

后端 未结 4 1600
后悔当初
后悔当初 2021-01-20 18:11

I ask a question about sum node\'s values:

sum some xml nodes values in sql server 2008

Please consider this code:

Declare @xml xml 
set @xml         


        
4条回答
  •  不思量自难忘°
    2021-01-20 18:58

    The XML you have here is untyped XML. That means the values provided to sum() is of type xdt:untypedAtomic. When sum() is used on xdt:untypedAtomic the values are cast to xs:double. The result of sum() is read by the values() function as a string (or untypedAtomic) and xs:double uses the scientific notation when the value is less than 1.0E-6, or greater than or equal to 1.0E6. SQL Server can not convert from scientific notation to int or bigint.

    Ref:
    sum Function (XQuery)
    Type Casting Rules in XQuery

    Other answers have provided workarounds that cast the input values or the result from sum() or using float as the data type in values(). Another option could be to use typed XML instead.

    Schema:

    create xml schema collection XSDSumTest as '
    
        
            
                
                    
                        
                            
                                
                                    
                                
                            
                        
                    
                
                
            
        
    '
    

    Query:

    declare @xml xml(XSDSumTest) = '
    
      1000000000 
      234650 
      0 
    '
    
    select @xml.value('sum(/Parent[@ID="p"]/Child)','bigint') as Sum
    

提交回复
热议问题