将数据 VARCHAR 转换为数字

CONVERTING DATA VARCHAR TO NUMERIC

示例数据:

12.12%,
6,
1,
10%,
8.347%,
16.27

代码

SELECT CONVERT(decimal(10,3), [Discount]) AS [Discount]
FROM [RDMS_DEV].[dbo].[t_TNSDiscount_dtl]

错误:

Error converting data type varchar to numeric.

预期结果:

12.12%,
6%,
1%,
10%,
8.347%,
16.27%

试试这个:您需要从折扣值中删除“%”。

DECLARE @tbl TABLE
(
    Id INT ,
    Discount VARCHAR(10)
)

INSERT INTO @tbl(Id, Discount)VALUES(1, '12.12%')
INSERT INTO @tbl(Id, Discount)VALUES(1, '6')
INSERT INTO @tbl(Id, Discount)VALUES(1, '1')
INSERT INTO @tbl(Id, Discount)VALUES(1, '10%')
INSERT INTO @tbl(Id, Discount)VALUES(1, '8.347%')
INSERT INTO @tbl(Id, Discount)VALUES(1, '16.27')


SELECT CONVERT(decimal(10,3), REPLACE([Discount],'%','')) AS [Discount] FROM @tbl

问题出在您的数据上,因为解决方案中的“%”字符通过替换功能将其删除。

SELECT CONVERT(varchar(255),REPLACE([Discount], '%', '')) + '%' AS [Discount] 
FROM [RDMS_DEV].[dbo].[t_TNSDiscount_dtl]

您还可以使用 add CONVERT(decimal(10,3), [Discount]) 强制保留 3 位小数。

New answer as the question changed: So for the update every time the data is greater and equal to 10, I concatenate '%' symbol.

SELECT CASE WHEN CONVERT(decimal,REPLACE([Discount], '%', '')) <  10 THEN CONVERT(varchar(255),REPLACE([Discount], '%', '')) ELSE
CONVERT(varchar(255),REPLACE([Discount], '%', ''))   + '%' END AS [Discount] 
FROM [RDMS_DEV].[dbo].[t_TNSDiscount_dtl]

Output result for updated question: