MySQL update syntax to convert column to custom format
-
15-06-2021 - |
質問
This question is related to another question, where I wanted to define a custom MySQL column format. The question is here: How to enforce custom MySQL column format.
The custom format that I want is always a 2 digit integer, followed by the # sign, then a space, then a decimal number with 2 digits after the decimal. Examples of allowed values are like this:
30# 11.00
27# 17.25
40# 17.25
values that are not allowed are like this:
30# 11
40# 20.5
27# 13
As you can see, the problem with the values that aren't allowed is basically just the last decimal number is missing the "." and trailing zeros. Is there some update syntax that I can use to fix all these incorrect column values? Basically I just need to check if the last decimal number after the "# " have the 2 trailing decimal digits. If it doesn't then I want to add the "." and the trailing zeros. Does anyone know an UPDATE
command that can do this?
Thanks!
EDIT
answers to some of the comments: Yes it is VARCHAR
type column. If the value is completely different than what we want, then just leave it alone. Most of the problems are what I explained, and if i can fix all of those with one query then that is a good start.
解決
update your_table
set some_column = case when len(some_column) = 6
then some_column + '.00'
when len(some_column) = 8
then some_column + '0'
end
where len(some_column) < 9;
See this example
here is some more precise syntax that worked very well:
update your_table
set some_column =
case
when length(some_column) = 6
then concat(some_column,".00")
when length(some_column) = 7
then concat(some_column,"00")
when length(some_column) = 8
then concat(some_column,"0")
else some_column
end
where some_column REGEXP '^[0-9][0-9]# [0-9][0-9]';