mySQL If statement - mysql

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 ;

Related

Sql trigger's query

I am trying to create custom id for my table in the following format
2 random alphabets - 00MaxID
for e.g: AA-001
I have tried writing a query for it but it is not working, this is my first time writing a trigger also writing a complex query such as this.
UPDATED-2
the following query gives me an error near "SELECT count(cus_id) INTO #ct FROM customer;"
CREATE
TRIGGER `id_gen` BEFORE INSERT
ON `testdb`.`customer`
FOR EACH ROW BEGIN
SELECT count(cus_id) INTO #ct FROM customer;
IF #ct < 1000 THEN
SET #cs_id = LPAD(#ct+1, 3, 0 );
ELSE
SET #cs_id = #ct+1;
END IF;
SET NEW.cus_id = CONCAT(CHAR(FLOOR(65 + RAND() * 26),FLOOR(65 + RAND() * 26)),'-',#cs_id);
END;
Error
SQL query: Documentation
CREATE
TRIGGER `id_gen` BEFORE INSERT
ON `testdb`.`customer`
FOR EACH ROW BEGIN
SELECT count(cus_id) INTO #ct FROM customer
MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 6
Executing with Trigger Section
Answered by #Solarflare.
In the screenshot, you can see that phpmyadmin automatically added code including for each row, which is now twice in the statement (thus the error). Your own code will start with begin.
BEGIN
SELECT count(cus_id)+1 INTO #ct FROM customer;
IF #ct < 1000 THEN
SET #cs_id = LPAD(#ct, 3, 0 );
ELSE
SET #cs_id = #ct;
END IF;
SET NEW.cus_id = CONCAT(CHAR(FLOOR(65 + RAND() * 26),FLOOR(65 + RAND() * 26)),'-',#cs_id);
END;

store function creation error in mysql #1064

I tried to create one function, ie if username exist, will return random number and character as a single string, but I tried below code, throwing syntax error like below, can u help to find the issue, I know that having issue in declaring string and returning string, but unable to find the issue. Thanks to the replies in advance
DELIMITER //
create function verifyEmail(userName varchar(25))
RETURNS TEXT
BEGIN
if EXISTS(select * from userdetails where name = userName)
then
SELECT #randomPass := select concat( char(round(rand()*36)+1), char(round(rand()*36)+1), char(round(rand()*36)+1));
return #randomPass;
else
return "not_exist";
end if;
end //
DELIMITER //
#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 'select concat( char(round(rand()*36)+1), char(round(rand()*36)+1), char(round(ra' at line 6
You are missing a closing ) on this line:
SELECT #randomPass := select concat( char(round(rand()*36)+1), char(round(rand()*36)+1), char(round(rand()*36)+1);
should be
SELECT #randomPass := select concat( char(round(rand()*36)+1), char(round(rand()*36)+1), char(round(rand()*36)+1));
Hooray, finally found answers.. This below code will help to solve the solution
DELIMITER //
create function verifyEmail(userName varchar(25))
RETURNS TEXT
BEGIN
DECLARE randomPass VARCHAR(8);
if EXISTS(select id from userdetails where name = userName)
THEN
SET randomPass = concat( char(rand()*25+65),char(rand()*25+65),char(rand()*25+65),char(rand()*25+65),char(rand()*25+65),char(rand()*25+65),char(rand()*25+65),char(rand()*25+65));
return randomPass;
else
return "not_exist";
end if;
end //
DELIMITER //

MySQL Syntax : "the right syntax to use near" - right in the beginning

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;

Assign In SELECT Command for MySQL Not working

I am trying to assign the #lastupd variable. as in below line:
select #lastupd := max(`last_edited_time`)
from flyspray_comments where task_id = taskID;
But mysql give me error:
ERROR 1064 (42000): 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 'BEGIN
set #lastupd = 0; select #lastupd := max(last_edited_time) from
flys' at line 2
The code:
delimiter $$
use flyspray $$
CREATE function last_upd_time(taskID INT)
BEGIN
set #lastupd = 0;
select #lastupd := max(`last_edited_time`) from flyspray_comments where task_id = taskID;
RETURN #lastupd;
END
$$
delimiter ;
Your immediate error has nothing to do with assignment. It is caused by the invalid definition of the function. You're missing mandatory RETURNS clause which indicates the return type of the function. See CREATE FUNCTION Syntax.
There is no need to use a variable in your case, less a user(session) variable. Just RETURN the result of the query.
And since you may use the only statement there is no need in a BEGIN ... END block and changing DELIMITER
That being said a streamlined and working version of your function may look like
CREATE FUNCTION last_upd_time(_task_id INT)
RETURNS DATETIME -- mandatory clause
RETURN -- just return the result of the query
(
SELECT MAX(last_edited_time)
FROM flyspray_comments
WHERE task_id = _task_id
); -- use default delimiter since it's a one-statement function
Here is SQLFiddle demo
Now, if you'd like to use a variable for some reason then
use a local instead of user(session) one.
assign a value with either SET or SELECT ... INTO syntax.
It may look like
DECLARE lastupd DATETIME DEFAULT NULL; -- or 0
SET lastupd =
(
SELECT MAX(last_edited_time)
FROM flyspray_comments
WHERE task_id = _task_id
);
or
DECLARE lastupd DATETIME DEFAULT NULL; -- 0
SELECT MAX(last_edited_time)
INTO lastupd
FROM flyspray_comments
WHERE task_id = _task_id;

using IF in MySQL (not the function)

I have what feels like a simple question, but can't seem to get it right. I'm just trying to execute a regular IF ... THEN ... logic, but can't seem to get it right:
set #var:=2;
if #var=1 THEN select 'hello';
I get:
ERROR 1064 (42000):
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 #var=1 THEN select 'hello'' at line 1
What am I missing?
You can use CASE instead.
SET #var:=2;
SELECT CASE WHEN #var=1 THEN 'hello' ELSE 'no hello' END;
--prints 'no hello'
SET #var:=2;
SELECT CASE WHEN #var:=1 THEN 'hello' ELSE 'no hello' END;
--prints 'hello'
I hope the idea is clear with above examples.
Edit: to address OP's additional concerns, You can incorporate selects in case statements, but you should enclose in brackets. For eg.
SET #var:=2;
SELECT CASE WHEN #var:=1 THEN (select 'hello') ELSE (select 'no hello') END;
One thing to notice is that it should return back only one value (from one row and a column)
You can, but only inside of functions, procedures and triggers like so:
DELIMITER //
DROP PROCEDURE IF EXISTS anyname//
CREATE PROCEDURE anyname()
BEGIN
IF #var1 = 1 THEN
SELECT 'hello';
END IF;
END//
SET #var1 := 1;
CALL anyname()//