MySQL IF Statements in Query issues - mysql

I have the following query that I am trying to execute. It is the starting point for a query required to run a report:
SET #fname = 'Bob';
SET #blah = 0;
SELECT CASE WHEN #fname IS NULL THEN #blah = 1 ELSE #blah END;
IF (#blah > 0) THEN
SELECT * FROM mytable
END IF;
Something is apparently wrong with my syntax but I cannot figure it out. I've written other queries using IF statements without issue. This will not run in either SQLyog or Workbench. It says there is a sytax error on "IF" with or without the parens, doesn't matter.
All I need is the ability to evaluate a variable/input parameter in the IF statement.
Any help is appreciated. NOTE - the SELECT CASE may not be necessary if I can get the IF to evaluate parameters properly but I was trying any possible solutions.
Thanks

You can use IF-THEN construction only inside BEGIN...END clause, which can be used only in procedures, functions, triggers, and events. It is impossible to use it in a simple script.
For your case I'd suggest this one -
SELECT * FROM mytable WHERE #blah > 0;

There needs to be a procedure or some form of script that needs to be executed given the case.
CALL procedure method needs to be initiated in the report datasource in such scenarios
Script can be written in following way: (Note: PROCEDURE can have parameters as required)
DELIMITER ?
CREATE PROCEDURE XYZ()
BEGIN
SET #fname = 'Bob';
SET #blah = 1;
SELECT CASE WHEN #fname IS NULL THEN #blah = 0 ELSE #blah END;
IF (#blah > 0) THEN
SELECT * from mytable;
END IF;
END ?
DELIMITER;
You can then pass the CALL XYZ() with or without parameters as required to your datasource or where you would pass your query to be executed for generating report.
Following works properly on MySQL Workbench. SELECT CASE query can be removed from the above procedure if not required.

I see issue with else statement:
SELECT CASE WHEN #fname IS NULL THEN #blah = 1 END;

// Using procedure getting result as per requirement
drop procedure abc;
DELIMITER //
create procedure abc()
begin
declare fname varchar(10);
declare blah int;
set fname = 'Bob';
set blah = 0;
if(fname IS not NULL) then
SELECT * from studmaster;
end if;
end //
DELIMITER ;
//--comment--> for execute procedure
call abc();

Not sure if this helps you much, but you can use if statement in an sql query
Select Blah.name,sum(Blah.quan) as SumofQuan, IF(Blah.descr LIKE '%searchterm%', "FOUND", IF(Blah.descr ="x", "x", "The Rest")) as New_DECRIPTION

I understand more of SQL SERVER, then it may be that my answer is not very helpful, but anyway here is my help:
Try changing the code snippet below,
SELECT #blah = (CASE WHEN #fname IS NULL THEN 1 ELSE #blah END)

In my view when using Sql server i found that the variable cannot assigned a value without declaring it..
I think you must have done as:
declare #fname nvarchar(50)
declare #blah int
then you must assign value to the variabl..
SET #fname = 'Bob'
SET #blah = 0
SELECT CASE WHEN #fname IS NULL THEN #blah = 1 ELSE #blah END;
IF (#blah > 0) THEN
SELECT * FROM mytable
END IF;

Related

Problem with comparison within a trigger statement using a variable gotten from query

I am trying to use an attribute from a 2nd table in the trigger of the 1st. To do this I am trying to load that value into a variable and then use it as a comparison.
However whenever I try and test the process the comparison answers false.
DELIMITER $$
create trigger evolve_persona before update on phantom_thieves
for each row begin
set #t := (select tier from persona where pname = old.persona);
if((new.persona != old.persona) and (select cast(#t as unsigned) = '1')) then
set
new.st = old.st+10, new.ma = old.ma+10, new.en= old.en+10, new.ag= old.ag+10,
new.lu= old.lu+20;
end if;
end$$
DELIMITER ;
I can see nothing wrong with your trigger but, this is somewhat more complicated as be written in a comment.
Make please following
SET #t = -1;
SELECT #t; -- returns -1
update phantom_thieves SET .....
SELECT #t; -should display at sometime 1
This seems to be the only problem that tier don't has the response 1 and with above, you can see what you get.

select statement intermittently returns null

So I have the following code in a stored procedure:
set #Id = (select id from foo where Name = 'bar');
IF #Id is null THEN
#add missing record
END IF;
However, its seems that the database will only return a value intermittently. Even when I know my select statement will return a record (copied and pasted directly out of my stored proc). Has anyone else had this issue with MySQL?
about the only crazy thing my proc is doing:
DECLARE CONTINUE HANDLER FOR 1062, 1452
but neither of those should effect my query (I am sure there is one and only one record)
Thanks
You can use a stored procedure like the following:
CREATE PROCEDURE example_proc (pName VARCHAR(10))
BEGIN
IF NOT EXISTS(SELECT 1 FROM foo WHERE Name = pName) THEN
INSERT INTO foo (Name) VALUES (pName);
END IF;
END
demo on dbfiddle.uk
SO i don't know why this fixed the problem, but it did.
By setting the variable to null first before the assignment seems to have fixed the problem. I was have the problem intermittently, so maybe I'm just lucking out longer than I did last time.

MySql Stored procedure WHERE "variabilised" according to a parameter

I'm totally new with stored procedure and I'm trying to understand its basic concepts. This is my first one and of course there is something wrong.
Basically the query is going to be the same (the original is more complex and there are other operations) but the WHERE clause changes according to the selType param. So what I'm trying to do is a sort of "variabilisation" of the WHERE clause according to the param value.
I don't know whether this is the correct approach and, if yes, what's wrong with it.
DELIMITER //
CREATE PROCEDURE `testProcedure` (IN addressId INT, IN selType BOOLEAN)
BEGIN
DECLARE whereUserCriteria VARCHAR(127);
IF selType = 1 THEN
SET whereUserCriteria = CONCAT('address_id = ', addressId);
ELSE
SET whereUserCriteria = 'address_id = 1';
END IF;
SELECT whatever
FROM wherever AS ad
WHERE whereUserCriteria ;
END //
It's nice to see that when it's not variabilised, it works perfectly but, as soon as i use a variable to make it dynamic, it stops working.
Of course this is a mere example aimed to understand what's the best approach in cases like this.
You can prepare query concatenating the queries and condition together and execute that using Prepared Execute statement as follows(as mentioned in the comment above):
DELIMITER //
CREATE PROCEDURE `testProcedure` (IN addressId INT, IN selType BOOLEAN)
BEGIN
DECLARE whereUserCriteria VARCHAR(127);
IF selType = 1 THEN
SET whereUserCriteria = CONCAT('address_id = ', addressId);
ELSE
SET whereUserCriteria = 'address_id = 1';
END IF;
SET #myQuery = '';
SET #myQuery = CONCAT("SELECT whatever FROM wherever AS ad
WHERE ",whereUserCriteria,") ;
PREPARE stmQuery FROM #myQuery;
EXECUTE stmQuery;
DEALLOCATE PREPARE stmQuery;
END //
DELIMITER ;
You probably want do dynamic query.
But you can rewrite your sample using CASE like this (but not sure if that is what you want):
SELECT whatever
FROM wherever AS ad
WHERE address_id = CASE WHEN selType = 1
THEN addressId
ELSE 1
END;

MySQL 5.5 Query Based on IF statement

I've been battling with this for too long so I'm here to ask for help...
I have a MySQL stored procedure that I want to do the following:
given an 'id' and a 'username' for a given record
if id does not exist in table then create record
else if id exists and username is not the same as what exists then update record
else do nothing
I've tried the following:
BEGIN
DECLARE doCreate INT;
DECLARE doUpdate INT;
SELECT COUNT(*) INTO doCreate FROM app_user WHERE id=1;
IF (doCreate > 0) THEN
SELECT COUNT(*) INTO doUpdate FROM app_user WHERE id=1 AND username='other';
END IF
IF(doCreate = 0) THEN ---SYNTAX ERROR ON THIS LINE---
SELECT 'CREATE';
ELSE IF(doUpdate = 0) THEN
SELECT 'UPDATE';
ELSE
SELECT 'NOTHING';
END IF
END
I've also tried replacing the if-elseif-else block with a case statement but get the same result...
CASE ---ERROR ON THIS LINE---
WHEN doCreate = 0 THEN
SELECT 'CREATE';
WHEN doUpdate = 0 THEN
SELECT 'UPDATE';
ELSE
SELECT 'NOTHING';
END
I seem to get a syntax error on anything that comes after the first END IF, so that's the first problem that occurs...
Any help would be appreciated - I'm sure there's a better way to do this.
I believe you'll need to terminate the END IFs with ;, and internally ELSEIF should be one word. Otherwise, another END IF is needed, but not found.
IF (doCreate > 0) THEN
SELECT COUNT(*) INTO doUpdate FROM app_user WHERE id=1 AND username='other';
END IF; /* terminate with ; */
IF(doCreate = 0) THEN
SELECT 'CREATE';
ELSEIF(doUpdate = 0) THEN
SELECT 'UPDATE';
ELSE
SELECT 'NOTHING';
END IF; /* terminate with ; */
Look over the MySQL IF/ELSE syntax reference for various usage examples.

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
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
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
The IF .. THEN .. ELSE syntax in MySQL is only available for procedural code (stored precudures, functions, triggers..), but not for SELECT statements.
IF ELSE USED IN STORED PROCEDURE EXAMPLE BELOW
DELIMITER //
CREATE PROCEDURE NAME(IN Number INT)
BEGIN
IF roll= 1
THEN SELECT * FROM table1 WHERE id = roll;
ELSE
SELECT * FROM table2 WHERE id = 2;
END IF;
END //
DELIMITER ;