sql-serverfor-xml

How to get SQL Server FOR XML to format float efficiently


When I use FOR XML to fetch values of type float from my SQL database, it formats them in scientific format, like this:

<foo bar="0.00000000e+000"/>

I would prefer it to say "0".

How can I persuade it to do this?


Solution

  • CAST is your friend

    declare @t table (bar float);    insert @t values (0);
    select bar from @t for xml path('foo');
    
    ------------------------------------------------
    | <foo><bar>0.000000000000000e+000</bar></foo> |
    
    
    declare @t table (bar float);    insert @t values (0);
    select CAST(bar as decimal(10,2)) bar from @t for xml path('foo');
    
    --------------------------------------------
    |               <foo><bar>0.00</bar></foo> |
    
    
    declare @t table (bar float);    insert @t values (0);
    select CAST(bar as bigint) bar from @t for xml path('foo');
    
    --------------------------------------------
    |                  <foo><bar>0</bar></foo> |