MySQL 5.5 Query Based on IF statement - mysql

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.

Related

MySql stored procedure rows issue

I have this stored procedure:
CREATE DEFINER=`admin`#`%` PROCEDURE `GetTickets4Card`(
IN p_TicketID int,
OUT p_returnvalue int
)
BEGIN
SELECT idbookingstickets
INTO #p_returnvalue
FROM bookingstickets
WHERE TicketId = p_TicketID;
/* Return value accordingly */
IF mysqll_affected_rows = 0 THEN SET p_returnvalue = 0;
/*
ELSE
SELECT * FROM BookingsTicketsCollected WHERE p_returnalue = idtickets;
if mysqll_affected_rows = 0 THEN SET p_returnvalue = -1;
END IF;
*/
END IF;
END
It gives me the following error: "Result consisted of more than one row". It may have something to do with mysql_affected_rows , but I have no idea, I want to know if the sql statement returns 1 row or not, any ideas?
Call code:
set #p_returnvalue = 0;
call yourTICKETbox_LIVE_DB.GetTickets4Card("aabb188e-6adc-11e5-9770-061de6653ea3", #p_returnvalue);
select #p_returnvalue;
When you use SELECT ... INTO variable, the query must return at most one row. If you only care whether there are any matching rows, you can use the EXISTS() function.
SET p_returnvalue = EXISTS(
SELECT 1
FROM bookingstickets
WHERE TicketId = p_TicketID);
BTW, the MySQL equivalent to the PHP function mysqli_affected_rows() is ROW_COUNT().

MySQL Create Trigger Syntax Error (Last Line)

I'm creating a MySQL trigger designed to update various tables with a new value if certain values are changed by an UPDATE query. I keep receiving the following syntax error for this particular trigger:
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 '' at line 29
Line 29 in this case is the line of the END statement.
This is my full code:
DELIMITER $$
CREATE TRIGGER update_selling_prices BEFORE UPDATE ON t1
FOR EACH ROW
BEGIN
DECLARE update_price INT DEFAULT 0;
DECLARE selling_price_1 DECIMAL(10, 3) DEFAULT 0.000;
DECLARE selling_price_2 DECIMAL(10, 3) DEFAULT 0.000;
IF (OLD.rrp_price <> NEW.rrp_price OR OLD.discount_1 <> NEW.discount_1 OR OLD.discount_2 <> NEW.discount_2 OR OLD.net_price <> NEW.net_price OR OLD.markup <> NEW.markup OR OLD.delivery_cost <> NEW.delivery_cost) THEN
SET update_price = (SELECT b.is_auto_update FROM price_categories c INNER JOIN brands b ON b.brand_name = c.brand_name WHERE c.id = NEW.category_id LIMIT 1);
IF (update_price = 1) THEN
IF (NEW.is_bundle = 0) THEN
UPDATE t2 SET temp = 'Fired Single' WHERE id = NEW.id;
ELSE IF (NEW.is_bundle = 1) THEN
UPDATE t2 SET temp = 'Fired Bundle' WHERE id = NEW.id;
END IF;
END IF;
END IF;
END;
$$
DELIMITER ;
The current UPDATE statements are just placeholders for some actual calculations I'll end up doing.
Please note: I use Sequel Pro for most MySQL-related stuff and initially was using their GUI to try and add the trigger - it automatically adds the surrounding code so I would only create everything between the BEGIN and END statements. That also resulted in this same syntax error, so I don't believe it's related to the delimiters like some similar threads I've already found on here. Nevertheless, I've tried adding the full trigger code via a normal query; changing the delimiter syntax - for example END$$, END $$, END; $$ etc.
I've successfully created other triggers with similar syntax, but they do not include the DECLARE syntax.
Where am I going wrong?
The problem is here:
IF (NEW.is_bundle = 0) THEN
UPDATE t2 SET temp = 'Fired Single' WHERE id = NEW.id;
ELSE IF (NEW.is_bundle = 1) THEN
UPDATE t2 SET temp = 'Fired Bundle' WHERE id = NEW.id;
END IF;
Review documentation: https://dev.mysql.com/doc/refman/8.0/en/if.html
MySQL supports ELSEIF and this is different than ELSE IF. If you use ELSEIF, this continues the structure of the IF statement. If you use ELSE IF, it starts a new IF statement, so it should be like this:
IF (NEW.is_bundle = 0) THEN
UPDATE t2 SET temp = 'Fired Single' WHERE id = NEW.id;
ELSE
IF (NEW.is_bundle = 1) THEN
UPDATE t2 SET temp = 'Fired Bundle' WHERE id = NEW.id;
END IF;
END IF;
See that there is a complete IF/THEN/END IF statement within the ELSE block of the outer one?
But you didn't do that, so the END IF applies to the innermost IF statement, and then you're one level off for the rest of the body of the trigger.
When MySQL gets to the end of the whole CREATE TRIGGER statement, if there aren't enough ENDs to balance the blocks you began, MySQL complains with the error you saw.

MYSQL Invalid use of group function How to resolve?

After creating trigger It started to displaying the Invalid use of group function error on update query.
Trigger:
CREATE TRIGGER header_true BEFORE UPDATE
ON category
FOR EACH row
begin
IF new.Header = 'True' THEN
SET new.H_order = max(old.H_order) + 1;
end IF;
end
Update Query:
UPDATE `category` SET `Header` = 'True' WHERE `category`.`ID` = 23
Anyone can please help me How can I resolve this issue?
You can try this solution for your problem :
MAX function is used to return the maximum value of an expression in a SELECT statement. MAX function is not possible without SELECT statement.
CREATE TRIGGER header_true BEFORE UPDATE
ON category
FOR EACH row
begin
IF new.Header = 'True' THEN
SET new.H_order = (select max(H_order) + 1 from category) + 1;
end IF;
end
I hope it will help.

How come this codes error? SQL Error code 1109: Unknown table 'o' in field list

When i run this code, it gives me error. From this code, there's several task to do:
(1) update tble customer by setting the address to '90 TYT' if c_id= 1
(2) view order_no,status,c_id,item_total remarks.
(3) if item_total 0, then update table order_status by setting remarks = 'UNAVAILABLE', else select order_no,status,item_total,remarks where status = 'waiting'.
Please help me fix the error. I'm new to SQL.
#drop procedure if exists usp_GetAnything;
delimiter //
create procedure usp_GetAnything()
begin
select c_id,lname,address,city
from customer;
update customer
set address = '90 TYT'
where c_id = 1;
select o.order_no,o.o_status,c.c_id,o.item_total,o.remarks
from customer c, order_status o
where c.c_id=o.c_id;
if (o.item_total > 0) then
update order_status o
set remarks = 'UNAVAILABLE'
where order_no > '123';
else
select order_no,o_status,item_total,remarks
from order_status
where o_status = 'waiting';
end if;
end
It's failing on the line:
if (o.item_total > 0)
o is unidentified outside of the previous select clause including all the selected variables.
In order to use the results that returned from the previous select you should select ... INTO...
(select the result arguments into declared local variables).
You can find here the following example:
DELIMITER //
CREATE PROCEDURE `proc_WHILE` (IN param1 INT)
BEGIN
DECLARE variable1, variable2 INT;
SET variable1 = 0;
WHILE variable1 < param1 DO
INSERT INTO table1 VALUES (param1);
SELECT COUNT(*) INTO variable2 FROM table1;
SET variable1 = variable1 + 1;
END WHILE;
END //
You can see that variable1 and variable2 are declared in the beginning of the procedure and later on used with select ... INTO ....

MySQL IF Statements in Query issues

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;