简体   繁体   中英

Converting a large decimal with percentage sign (%) to a smaller decimal

I have the following data that I need to convert to a simple decimal. Currently, it is in varchar format. The data is in a column called Commission%

Commission% (currently Varchar) Commission% V2 (needs to be decimal)
87.00000% .87
95.00000% .95

I have tried the following:

CAST(CAST(CONVERT(FLOAT,REPLACE([Commission %], ''%'', '''')) / 100 AS DECIMAL(10,6)) as DECIMAL(10,6))

BUT I get the following error message Error converting data type varchar to numeric . I was able to use something similar the other day but there were fewer trailing zero's at the time.

This is almost certainly due to bad data which is what you should expect when you store numbers as strings. Here is how you identify them:

SELECT [KeyColumn], [Commission%] 
  FROM dbo.BadColumnNamesWow
  WHERE [Commission%] IS NOT NULL
    AND TRY_CONVERT(decimal(20,10), REPLACE([Commission%], '%', '')) IS NULL;

Since you now say there are other patterns, it might make sense to just do this to identify all of the bad data:

SELECT * FROM dbo.BadColumnNamesWow
  WHERE [Commission%] IS NOT NULL
    AND PATINDEX('%[^0-9.]%', [Commission%]) > 0;

Then clean it up. This should be a lesson in why you never store numeric values in string columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM