0

I tried this select query with an IF statement but it didn't work,

Have you any solution

thank you

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `myProcedure`()
BEGIN
   set @sql=' Select IF(field1 = 1, \'Oui\', IF(field2 != 0 and field1 = 0,\'En 

    cours\', IF(field2 = 0 and field1 = 0,\'non\', \'non\'),\'non\'))  as Payed
    from myTable';

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

   END$$
DELIMITER ;

error message :

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 '),'non')) as Payed
1
  • You Can Use Case Statement instead of IF. Commented Aug 23, 2016 at 10:25

1 Answer 1

1

This answer may not fix your direct problem, but if you use CASE statements, the logic gets a bit easier to read:

SELECT CASE WHEN field1 = 1 THEN 'Oui'
            WHEN field2 != 0 AND field1 = 0 THEN 'Encours'
            ELSE 'non'
       END AS Payed
FROM myTable

The ANSI compliant way to escape a single quote is by using two of them, e.g. ''. So your @sql variable would then look something like this:

SET @sql= 'SELECT CASE WHEN field1 = 1 THEN ''Oui''
        WHEN field2 != 0 AND field1 = 0 THEN ''Encours''
            ELSE ''non''
       END AS Payed
FROM myTable';
Sign up to request clarification or add additional context in comments.

2 Comments

@Shadow Part of the OP issue is using IF, which requires many layers of nested parentheses. I don't usually undelete a downvoted answer, but I did in this case because I think using CASE would solve two problems at once.
My downvote was due to the explanation that if() function cannot be used the way it was used in the OP. Since you corrected the answer, I withdraw the downvote.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.