2

我有以下变量:

DECLARE @test nvarchar(100)
SET @test =  'Prodcut A (Average: 1.000)'
SET @test =  'Prodcut B (Average: 2.3500)'

我的输出应该是:Prodcut A(平均:1.0),Prodcut B(平均:2.35)

如何从 SQL Server 中的 nvarchar 数据类型列中删除所有尾随零?我确信我必须使用 SUBSTRING 和 CHARINDEX 但不确定如何使用。有人可以帮帮我吗?

我尝试了以下方法:

IF charindex('.', @test ) > 0 
   select  SUBSTRING(@test, PATINDEX('%[^0 ]%', @test+ ' '), LEN(@test))                    
End
4

5 回答 5

1

您可以遍历字符串以查找最后一个非“0”字符的位置,但这很麻烦。

需要注意的是,您可能会偶尔遇到浮点错误,这将满足您的需求:

convert(varchar, convert(float, '123.40')) -- yields '123.4'
convert(varchar, convert(float, @test))
于 2013-09-20T20:30:11.290 回答
1

如果结构始终相同,您可能会使用以下内容:

Declare @a Table (test varchar(100))
Insert into @a Values ('Prodcut X ')
Insert into @a Values ('Prodcut A (Average: 1.000)')
Insert into @a Values ('Prodcut B (Average: 2.3500)')
Insert into @a Values ('Prodcut C (Average: 2.0510)')


Select  
Case When charindex('.', test ) > 0 then
   LEFT(test, LEN(test) + 1  - 
   Case When 
      PATINDEX('%[1-9]%', Reverse(test) + ' ')
    > PATINDEX('%[.]%', Reverse(test) + ' ')
    then PATINDEX('%[.]%', Reverse(test) + ' ') - 1
    else PATINDEX('%[1-9]%', Reverse(test) + ' ') 
    end 
    ) +')'
else test end
from @a
于 2013-09-20T20:36:19.960 回答
0

Assuming

Yes. The column is defined as NVARCHAR the values sometimes be like "Average:" + number + ")"

you can convert number from decimal type to float, because float is printed without trailing zeros:

'Average:' + cast(number as float) + ')'

But there's a known localization problem (i.e. it appears for some non-English versions, e.g. for Russian version) when decimal has . as separator and float type has ,. In this case you need:

'Average:' + replace(cast(cast(number as float) as nvarchar), ',', '.') + ')'

, i.e. to replace comma to dot.

于 2013-09-20T22:12:31.937 回答
0

请尝试以下代码。

DECLARE @test nvarchar(100)
SET @test =  'Prodcut A (Average: ' + CONVERT(VARCHAR,CAST(1.000 as float))+')'

SELECT @test
于 2015-09-11T12:33:48.243 回答
0

尝试这个

 DECLARE @test nvarchar(100)
SET @test =  'Prodcut A (Average: ' + CONVERT(VARCHAR,CAST(1.000 as float))+')'
SET @test =  'Prodcut B (Average: ' + CONVERT(VARCHAR,CAST(2.3500 as float))+')'
SELECT @test
于 2015-09-09T08:39:58.550 回答