我有一些作为nvarchar传入的数据。显然,数据最初是从基于数字的数据类型转换而来的。例如,我的值是17.0000000。我想去掉这些尾随的零,这样它就是"17“。我确实需要varchar或nvarchar格式的输出。
发布于 2017-10-26 00:18:07
之后,您可以使用以下命令删除小数和零:
select (case when col like '%.0%' and col not like '%.%[^0]%'
then left(col, charindex('.', col) - 1)
when col like '%.%0'
then replace(rtrim(replace(col, '0', ' ')), ' ', '0')
else col
end)注意:这假设该值是严格的数字(因此没有自己的空格)。
但是,我建议您将该值转换为适当的numeric/decimal类型。
发布于 2017-10-26 00:29:31
如果使用2012+,还有另一种选择
示例
Declare @YourTable Table ([StrValue] varchar(50))
Insert Into @YourTable Values
('17.00000')
,('17.10000')
,('.1')
,('.0')
,('Cat')
,('07/29/2017')
Select *
,NewVal = coalesce(convert(varchar(50),try_convert(float,StrValue)),StrValue)
From @YourTable返回
StrValue NewVal
17.00000 17
17.10000 17.1
.1 0.1
.0 0
Cat Cat
07/29/2017 07/29/2017发布于 2017-10-26 00:24:55
SELECT LEFT('17.0000000',CHARINDEX('17.0000000','.')-1)我在这里对该值进行了硬编码,但您可以将其替换为您的列名
https://stackoverflow.com/questions/46937374
复制相似问题