Re: update and control flow
- Date: Tue, 09 Dec 2014 10:54:37 -0500
- From: "shawn l.green" <shawn.l.green@xxxxxxxxxx>
- Subject: Re: update and control flow
On 12/9/2014 9:25 AM, Martin Mueller wrote:
I'm trying to get my feet wet with 'if' and 'when' uses in mysql. it would
be very useful for update operations, but I can't get it right.
If I read the documentation correctly, it should be possible to say
if WORD like 'a%' SET COMMENT = 'a'
elseif WORD like 'b%' SET COMMENT = 'b'
But this gives me an error message. What am I doing wrong?
The correct syntax is to put the function after the = sign. The column
name must appear by itself on the left side of the equation. You must
also use the function-format of IF or a CASE..END construction.
SET COMMENT = IF(WORD like 'a%','a',if(WORD like 'b%', 'b',COMMENT))
SET COMMENT = CASE
WHEN WORD like 'a%' then 'a'
WHEN WORD like 'b%' then 'b'
But, as you noted, it may be more efficient to simply run two UPDATE
statements each with the appropriate WHERE clause to limit the changes
to just those rows that match your conditions.
SET COMMENT = 'a'
WHERE WORD like 'a%'
And you can combine both techniques to limit the scope of the UPDATE to
just the rows to change by matching either pattern.
SET COMMENT = IF(WORD like 'a%','a','b')
WHERE WORD like 'a%' or WORD like 'b%'
Note: this last format doesn't need the second if() in the 'else'
portion of the first IF() function because the set of rows to be
operated on is already limited by the WHERE clause. The rows will match
one condition or the other but not neither.
MySQL Senior Principal Technical Support Engineer
Oracle USA, Inc. - Hardware and Software, Engineered to Work Together.
Office: Blountville, TN
MySQL General Mailing List
For list archives: http://lists.mysql.com/mysql
To unsubscribe: http://lists.mysql.com/mysql