MySql Use replace() in if() condition

I have tried:

SET @my_var = 'one,two,three';
SET @to_replace = 'two,';
SET @my_check = 1;

SET @my_var = SELECT IF(
    ISNULL(@my_check),
    @my_var,
    REPLACE(@my_var, @to_replace,'')
);

I have tried also SET @my_var = IF( ... Or SELECT REPLACE instead REPLACE in condition

But got syntax error

What I expect is:

If @my_check = null so @my_var = 'one,two,three' (still unchanged)

Else replace two, with '' but using @to_replace variable

Expected result: @my_var = 'one,three'

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

set @my_var = if(isnull(@my_check), @my_var, replace(@my_var, @to_replace, ''));

Works well in MySQL v8.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x