从表SQL Server创建字符串时丢失较少的数字

时间:2011-09-03 05:05:42

标签: string sql-server-2008 select

我有一张包含0.681672875510799

等双打的表格

所以例如一个虚拟表:

a1      a2
-------------------------
1      0.681672875510799
NULL    1
NULL    NULL
NULL    NULL
NULL    NULL
NULL    NULL

当我这样做时

DECLARE @CommaString nvarchar(max)
SET @CommaString = ''
SELECT @CommaString = 
STUFF(
(SELECT  ',' + CAST([col] AS VARCHAR) FROM (
 SELECT [a1] AS col FROM [ta] UNION ALL 
 SELECT [a2] AS col FROM [ta] 
) alldata FOR XML PATH('')  )  ,   1  ,   1  ,  '' )
PRINT @CommaString;

打印:

1,0.681673,1

所以我丢失了几个小数,这也很重要,我如何修改代码来获取 1,0.681672875510799,1代替1,0.681673,1

2 个答案:

答案 0 :(得分:1)

您的问题是您在不指定大小的情况下转换为varchar,您需要执行CAST([col] AS VARCHAR(max)

DECLARE @CommaString nvarchar(max)
SET @CommaString = ''
SELECT @CommaString = 
STUFF(
(SELECT  ',' + cast(CAST( [col] as decimal(22,19)) as varchar(30)) FROM (
 SELECT [a1] AS col FROM [#ta] UNION ALL 
 SELECT [a2] AS col FROM [#ta] 
) alldata FOR XML PATH('')  )  ,   1  ,   1  ,  '' )
PRINT @CommaString;

问题是,即使对于整数值,您也会得到很多零作为小数。如果你关心的话,你可能需要做一些其他的转变。

编辑:包括我的表格定义:

create table #ta 
(
   a1 int,
  a2 float
)

编辑:再次将我的表定义从十进制更改为浮动列b并在我的查询中添加了双重转换。

现在产生:1.0000000000000000000,1.0000000000000000000,0.6816728755107990500

答案 1 :(得分:1)

在你的内部查询中:

SELECT  ',' + CAST([col] AS VARCHAR) 
FROM (
  SELECT [a1] AS col FROM [ta] 
  UNION ALL 
  SELECT CAST([a2] AS DECIMAL(18,15)) AS col FROM [ta]

将FLOAT转换为DECIMAL对我有用(SQL Server 2008 R2)。您可能需要调整(18,15)来处理数据。

注意到还有一件事可行(并且可能更一致):

SELECT  ',' + CONVERT(varchar(max), col, 128)
FROM (
  SELECT [a1] AS col FROM [ta] 
  UNION ALL 
  SELECT [a2] AS col FROM [ta]