Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mySQL If statement

I am trying to make this If Statement work, but I can't seem to make it do what I want. If I do a select @result, It'll give me the value 0, then why doesn't the IF statement work?

SET @message = '((sometihng here))';
select LEFT(@message, 1) into @firstChar;
select STRCMP(@firstChar,'(') into @result;
IF (@result = 0) THEN  
SET @message = 'true';
//more selects and cals here;
END IF;
select @message;

I should get true, but I don't it shows me an error:

SQL query: IF( @result =0 ) THEN SET @message = 'true';

MySQL said:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF (@result = 0) THEN SET @message = 'true'' at line 1

like image 685
Myy Avatar asked Mar 28 '12 22:03

Myy


People also ask

How do I write an if statement in MySQL?

MySQL IF-THEN-ELSEIF-ELSE statement The syntax is given below: IF condition THEN statements; ELSEIF elseif-condition THEN elseif-statements; ... ELSE else-statements; END IF; Let's review each block.

Can we use if condition in MySQL?

MySQL IF() FunctionThe IF() function returns a value if a condition is TRUE, or another value if a condition is FALSE.

Can I use if in SQL query?

IF statements can be used to conditionally enter into some logic based on the status of a condition being satisfied. The IF statement is logically equivalent to a CASE statements with a searched-case-statement-when clause.

Can you put an if statement in a query?

The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query: SELECT IF(JQ.


2 Answers

try use function http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if

SELECT IF(@result = 0, 'true', '((something here))') AS message
like image 145
Vlad Miller Avatar answered Sep 22 '22 21:09

Vlad Miller


As Max Mara pointed out, that's a good work aroud. The reason the IF wasn't working is not because the syntax is incorrect, but because flow control functions like IF ... THEN are only valid inside of stored procedures or functions, All this thanks to @TehShrike

like image 45
Myy Avatar answered Sep 21 '22 21:09

Myy