当CAST为NVarChar时删除尾随0

时间:2016-01-13 17:29:57

标签: sql sql-server sql-server-2008 tsql

我的数据为Decimal(15,4),值可以是14.010014.000014.9999

为了与其他系统集成,我们必须在NVarChar(MAX)属性表中存储此类数据。当我运行CAST(Field AS NVarChar(MAX))时,我会收到类似0.0000

的字符串值

我想要的是从这些字符串中修剪尾随零(以及句点,如果需要),因为以后在在线传输中使用数据,发送14代替14.0000 <更好/ p>

我该怎么做?

5 个答案:

答案 0 :(得分:2)

SQL Server 2012+您可以使用FORMATSQL Server 2008可以使用字符串操作:

CREATE TABLE #tab(col DECIMAL(15,4));

INSERT INTO #tab(col)
VALUES (14.0100), (14.0000),
       (14.9999), (10), (0),
       (-1), (-10), (-12.01), (-12.10);

SELECT 
  col
 ,result_2012 = FORMAT(col, '########.####') 
 ,result_2008 = CASE 
                 WHEN col = 0 THEN '0'
                 ELSE LEFT(col,LEN(col) - 
                        CASE WHEN PATINDEX('%[1-9]%', REVERSE(col)) < PATINDEX('%[.]%', REVERSE(col))
                             THEN PATINDEX('%[1-9]%', REVERSE(col)) - 1 
                             ELSE PATINDEX('%[.]%', REVERSE(col))
                        END)
               END
FROM #tab;

LiveDemo

答案 1 :(得分:0)

您可以尝试在转换之前将十进制数字转换为浮点数,然后将它们转换为NVarChars i.e. CAST(CAST(Field as Float(8)) as NVarChar(MAX)).您可能遇到的唯一问题是,如果任何现有数字的精度高于8字节浮点数可以处理的数字这应该很容易检查。

在使用case语句将数字作为字符串转换后,也可以删除多余的零,即

case when right(Field, 4) = '0000' then
 left(Field, len(Field) - 5) -- -5 to remove the decimal point
else case when right(Field, 3) = '000' Then
 left(Field, len(Field) - 3)
else case when right(Field, 2) = '00' Then
 left(Field, len(Field) - 2)
else case when right(Field, 1) = '0' Then
 left(Field, len(Field) - 1)
end end end end 

答案 2 :(得分:0)

--With a lot of fantasy
--Tip: to optimize performances, first select values in a @-table, then do this transformation.
select 
left( cast(Field  as varchar(max)), charindex('.', cast(Field  as varchar(max))) - 1) + 
Case when reverse(cast(cast(reverse(substring(cast(Field  as varchar), charindex('.', cast(Field  as varchar)) + 1 ,4)) as int) as nvarchar)) = 0 Then '' Else
'.' + reverse(cast(cast(reverse(substring(cast(Field  as varchar), charindex('.', cast(Field  as varchar)) + 1 ,4)) as int) as nvarchar)) End

答案 3 :(得分:0)

简单转换为REAL然后返回varch(max)如果你想删除前导0,如下所示:

declare @a as Decimal(15,4)=14.0010
select cast(cast (@a as real) as varchar(max)) as a2
-- ouptut is 14.001
declare @a as Decimal(15,4)=14.0000
select cast(cast (@a as real) as varchar(max)) as a2
-- output is 14

答案 4 :(得分:0)

这里的想法是使用修剪空间的内置字符串函数从转换后的十进制中调整TRIM ZERO,如下所示:

declare @d as Decimal(15,4)=11400012.00000, @s0 VARCHAR(MAX), @s VARCHAR(MAX)
set @s0=cast(@d as varchar(max))
set @s=left(@s0,len(rtrim(replace(@s0,'0',' '))))
if right(@s,1)='.' set @s=left(@s,len(@s)-1)
select @s
-- returns 11400012.001

您还可以定义为您执行此任务的功能:

CREATE FUNCTION TRIM0(@s0 varchar(max))
RETURNS varchar(max)
AS
BEGIN
    declare @s varchar(max)=''
    set @s=left(@s0,len(rtrim(replace(@s0,'0',' '))))
    if right(@s,1)='.' set @s=left(@s,len(@s)-1)
    return @s
END