I am trying to execute this code
set #id = 0;
set #the_number = 0;
set #the_message = 0;
set #selected_message = 0;
SELECT id, dest_msisdn, text_message INTO #id, #the_number, #the_message FROM incoming_sms where service_id = 6015592000101762 AND job_status = 0 limit 1;
if(#the_message LIKE '%Bank%')then
select 'h';
end if;
but i keep getting an error on
if(#the_message LIKE '%Bank%')then
select 'h'' at line 1
Why is my if producing an error?.
You need to put your code inside of a strored procedure or function to use the IF statement https://stackoverflow.com/a/12954385/5308054. Here you can see a feature request to fix it https://bugs.mysql.com/bug.php?id=48777
It is possible to rewrite query without IF statements but I think this question is too to be answered in such way.
Related
Srr can someone help me
i have next query for giving me the number of rows in a table
SET #UUIDTEST2 = 100;
SET #TESTNUMBER = 0;
SELECT #UUIDTEST2;
SELECT #UUIDTEST2 := count(*) from `swennenhome`.`tb_ElectrititeitLog` ;
SELECT #UUIDTEST2
This works BUT, when i add a if END IF Like this
SET #UUIDTEST2 = 100;
SET #TESTNUMBER = 0;
SET #TESTNUMBER = 0;
SELECT #UUIDTEST2;
SELECT #UUIDTEST2 := count(*) from `swennenhome`.`tb_ElectrititeitLog` ;
if (#UUIDTEST2 = 0) then
SET #TESTNUMBER = 5;
end if ;
SELECT #UUIDTEST2
i receive always a SQL syntax error.
I have be searching on google for 2 day's now and can't find the problem or a solution.
IF statement can be used in compound statement only.
Rather than IF function.
-- ...
SELECT #UUIDTEST2 := IF(count(*), count(*), 5)
from `swennenhome`.`tb_ElectrititeitLog`;
SELECT #UUIDTEST2;
But in your case, you may avoid using IF:
-- ...
SELECT #UUIDTEST2 := COALESCE(NULLIF(count(*), 0), 5)
from `swennenhome`.`tb_ElectrititeitLog`;
SELECT #UUIDTEST2;
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().
I am a MySQL-noob and today I tried to setup a MySQL call which is more than 5 lines long. I keep getting syntax errors which I try to fix for hours, but I don't have a clue what the problem is. Here is the code:
USE myDatabase;
DELIMITER //
CREATE PROCEDURE MYPROC()
BEGIN
SET #ID = 1;
SET #maxID = 3;
CREATE TEMPORARY TABLE resultTable(v DOUBLE, ttc DOUBLE);
WHILE (#ID < #maxID) DO
INSERT partTable1.v, partTable2.ttc
INTO
resultTable
FROM
(SELECT * FROM
(((SELECT time_sec, v FROM speedTable WHERE (trip_id = #ID)) as partTable1)
INNER JOIN
((SELECT time_sec, ttc FROM sightsTable WHERE (trip_id = #ID)) as partTable2) ON
(0.04 > abs(partTable1.time_sec - partTable2.time_sec)))
);
SET #ID := #ID + 1;
END WHILE;
END //
DELIMITER;
CALL MYPROC();
SELECT * FROM resultTable LIMIT 100;
Is there anything obvious that needs to be corrected?
Update1: Added semicolon to the "CREATE.."-statement, now first three statements are OK.
Update2: Added 3 more semicolons!
Update3: Followed the suggestion to make it a function + separate function call. Error message changed!
Update4: I fixed the issues mentioned in the two answers. Still something wrong there. See updated code above and error message below.
Updated error message:
ERROR 1064 (42000) at line 4: You have an error in your SQL syntax; check the ma
nual that corresponds to your MySQL server version for the right syntax to use n
ear ' partTable2.ttc
INTO
resultTable
FROM
(SELECT * FROM
(((SELE' at line 11
Kind Regards,
Theo
Flow control statements, of which WHILE is one, can only be used within a stored procedure, but you are attempting to use it as a plain query via the console.
If you absolutely must take this path (using mysql instead of an application language), create a store procedure with the code you want, then call it.
Creating the procedure would look like this:
DELIMITER //
CREATE PROCEDURE MYPROC()
BEGIN
WHILE (#ID < #maxID) DO
SET #partTable1 = (SELECT time_sec, v FROM speedTable WHERE (trip_id = #ID));
SET #partTable2 = (SELECT time_sec, ttc FROM sightsTable WHERE (trip_id = #ID));
INSERT v, ttc INTO resultTable FROM
(#partTable1 INNER JOIN #partTable2 ON
(0.04 > abs(partTable1.time_sec - partTable2.time_sec)));
SET #ID := #ID + 1;
END WHILE;
END//
DELIMITER ;
Then to call it:
CALL MYPROC();
See this SQLFiddle of a simplified version of this working.
Note that you do have one syntax error:
#ID = #ID + 1; -- incorrect syntax
SET #ID := #ID + 1; -- correct
Still some syntactic problems and functionality problems...
You can't use WHILE in SQL scripts. You can use WHILE only in the body of a stored routine. See http://dev.mysql.com/doc/refman/5.6/en/flow-control-statements.html
You can't use SET to assign multiple columns to a scalar. MySQL doesn't support relation-valued variables, only scalar variables. See http://dev.mysql.com/doc/refman/5.6/en/set-statement.html
You can INSERT from the results of a query with a join, but the query must be introduced with SELECT. See http://dev.mysql.com/doc/refman/5.6/en/insert-select.html
You can't use session variables as the names of tables. You would have to use a prepared statement. See http://dev.mysql.com/doc/refman/5.6/en/prepare.html But that opens a whole different can of worms, and doing it wrong can be a security vulnerability (see http://xkcd.com/327). I wouldn't recommend you start using prepared statements as a self-described MySQL-noob.
This problem is probably simpler than you're making it. You don't need a temporary table, and you don't need to read the results one row at a time.
Here's an example that I think does what you intend:
USE myDatabase
SET #ID = 1;
SET #maxID = 3;
SELECT sp.v, si.ttc
FROM speedTable AS sp
INNER JOIN sightsTable AS si
ON (sp.trip_id = si.trip_id AND 0.04 > ABS(sp.time_sec - si.time_sec))
WHERE sp.trip_id BETWEEN #ID AND #maxID;
I've got MySQL procedure which I execute in MySQL Workbench. The problem is that it generates many new result-set, and GUI client show it (...many times) -
I found solution, which I can use instead just select clause to avoid generating result-sets. It looks like:
SELECT EXISTS(
SELECT ...
)
INTO #resultNm
Unfortunately it won't work with LIMIT ?,1 where ? is my variable 'i'. I also cant use just 'i' instead % because I am working on MySQL 5.1 (and limit clauses can't be done in other way). So my question - are other possibilities to hide result-sets?
CREATE PROCEDURE LOOPDOSSIERS(starter integer, finish integer)
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE row_oid binary(16);
DECLARE row_str VARCHAR(256);
DECLARE row_old VARCHAR(256);
SET i=starter;
WHILE i<finish DO
-- SET row_str = ();
SET #row_str = 'select CAST(concat(d.prefixe_numero,d.numero) as CHAR) from courrier_concerne_dossier as x
join dossier as d on
d.oid = x.dossier_oid limit ?,1';
PREPARE stmt1 FROM #row_str;
EXECUTE stmt1 USING #i;
SET #row_oid = 'select x.courrier_oid
from courrier_concerne_dossier as x
join dossier as d on
d.oid = x.dossier_oid LIMIT ?,1';
PREPARE stmt2 FROM #row_oid;
EXECUTE stmt2 USING #i;
select dossiers_str from courrier_envoye where oid = row_oid into row_old;
update courrier_envoye set dossiers_str = CAST(CONCAT(row_str, " ", row_old) AS CHAR) where oid = row_oid;
SET i = i + 1;
END WHILE;
End;
;;
LIMIT without an ORDER BY clause doesn't have a well defined behavior. For your parameters to work in a sensible way, you'll need to order by something. The starter and finish variables aren't very meaningful at the moment, but it's currently not clear what they're intended to be.
I think you can probably accomplish this whole procedure in a single query using the syntax in this answer (also probably much faster). That probably won't work with LIMIT, but I'd highly recommend using a range of some kind in the where clause rather than a limit anyway.
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;