1

I have a column of percentages, expressed as follows:

----------
usertxt2
----------
25%
26
NULL
a%

23.00%
23.6578

I need to convert all numbers to a fixed format of xx.xx% so that the column would appear as

----------
usertxt2
----------
25.00%
26.00%
NULL
NULL
NULL
23.00%
23.66%

So far, I have tried initially removing the LEFT() function to remove the % character then converting to decimal using the CAST() function and using the CASE WHEN function to ignore blank, non-numeric characters and NULL values. How can I remove the % character and convert to numeric whilst ignoring the blank and non-numeric characters?

1
  • You better store numbers in numeric columns. Storing them in varchar is asking for trouble. Jul 26, 2018 at 20:17

1 Answer 1

1

Here is one method:

update t
    set usertxt2 = cast(try_cast(replace(usertxt2, '%', '') as decimal(5, 2)) as varchar(255)) + '%'

This uses try_cast() to detect valid numbers.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.