using IF in MySQL (not the function) - mysql

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()//

Related

mysql trigger syntax error in maria db

I was trying to make one trigger , so that i can check for any negative insertion of age .
I tried below query but its showing below error .
CREATE TRIGGER agecheck
BEFORE INSERT ON people
FOR EACH ROW
BEGIN
(CASE WHEN people.age > 0 THEN people.age ELSE 0 END )
END
ERROR CODE:
#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 'CASE WHEN people.age > 0 THEN 1 ELSE 0 END )
END' at line 5
Am i doing anything wrong in the syntax?
The statement you have in your trigger is not a statement. It's just an expression. This is not a thing you can use as a statement by itself.
I'm just guessing at what you are trying to do: make sure age is not negative. You could probably do this by declaring the column as TINYINT UNSIGNED, but if you want to do it with a trigger:
FOR EACH ROW
BEGIN
SET NEW.age = CASE WHEN NEW.age > 0 THEN NEW.age ELSE 0 END;
END
In a trigger, always reference the columns of the respective triggered row with NEW.<columnname> or OLD.<columnname>.
Another expression that works just as well:
FOR EACH ROW
BEGIN
SET NEW.age = GREATEST(NEW.age, 0);
END
There's no specific advantage for this alternative, I'm just showing another use of an expression.

stored procedure is issuing syntax error

I am trying to create a mysql stored procedure with phpmyadmin:
CREATE PROCEDURE AddTableColumn()
BEGIN
IF (SELECT COUNT (table_name)
FROM information_schema.tables
WHERE table_name IN ('authors', 'publishers') = 2 )
print 'specified tables exist...';
ELSE
print 'specified tables unavailable...';
END IF;
END​
above code is a snippet that should search information schema
for the availability of authors and publishers tables,
then proceed to add new column in each table if present.
the print statement was for debug purpose. when i clicked the
GO command, here's the error message :
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 'print 'avail...'; ELSE print 'unavail...'; END IF; END' at line
7.
what am i doing wrong ? i have even tried other code as a test,
all failing with the same error. code as simple as:
BEGIN
IF (6 > 4)
print 'greater';
ELSE
print 'lesser';
END IF;
END ​
all failed. any help will be appreciated.
'print' is not recognized in MySQL.
If you want to read back the output, just use a select in the SP.
Change part of your SP as below:
DECLARE found_status VARCHAR(255) DEFAULT NULL;
IF ....
SELECT 'specified tables exist...' INTO found_status;
ELSE
SELECT 'specified tables unavailable...' INTO found_status;
END IF;
SELECT found_status;

In MySQL, can I use procedural SQL outside a stored procedure?

In Sybase ASE and Microsoft SQL Server, you can use procedural SQL (control flow statements like IF/ELSE and WHILE, declaring and setting lexical variables, and so on) in one-off SQL statement batches, like so:
-- from https://msdn.microsoft.com/en-us/library/ms182587.aspx
DECLARE #Number INTEGER;
SET #Number = 50;
IF #Number > 100
SELECT 'The number is large.' AS large;
ELSE
BEGIN
IF #Number < 10
SELECT 'The number is small.' AS small;
ELSE
SELECT 'The number is medium.' AS medium;
END;
You can send this code directly to SQL Server, without preparing it or putting it in a stored procedure, and SQL Server will send back a table with a single tuple and column, with the value "The number is medium."
From what I can tell, in MySQL, procedural SQL code is restricted to appearing only within stored procedure definitions (CREATE PROCEDURE or CREATE FUNCTION statements):
mysql> delimiter //
mysql> if 32 = 32 then
-> select 'yes';
-> else
-> select 'no';
-> end if;
-> //
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 32 = 32 then
select 'yes';
else
select 'no';
end if'
at line 1
Is this impression correct?
Yes, you are correct. Lots of constructs are only valid inside stored functions, like if. It even says so in the manual.
"The IF statement for stored programs implements a basic conditional construct."
However, the same result can be achieved using another approach, with the function if
select if(32 = 32, 'yes', 'no');
sqlfiddle

Mysql error: Not allowed to return a result set from a function

I am trying to have a conditional change in a parameter for update statement.
I am getting the following error when I try the following function
/home/y/bin/mysql -u root < testpri.sql > out
ERROR 1415 (0A000) at line 4: Not allowed to return a result set from a function
Contents of testpri.sql are as follows:
use `zestdb`;
DROP FUNCTION IF EXISTS UPDATEPASSWD;
DELIMITER //
CREATE FUNCTION UPDATEPASSWD(n INT) RETURNS varchar(255) DETERMINISTIC
BEGIN
DECLARE mypasswd varchar(255);
IF (n = 1) THEN
SET mypasswd = '12ccc1e5c3c9203af7752f937fca4ea6263f07a5';
SELECT 'n is 1' AS ' ';
ELSE
SET mypasswd = '1a7bc371cc108075cf8115918547c3019bf97e5d';
SELECT 'n is 0' AS ' ';
END IF;>
SELECT CONCAT('mypasswd is ', mypasswd) AS ' ';
RETURN mypasswd;
END //
DELIMITER ;
CALL UPDATEPASSWD(0);
What am I missing?
I think it's actually your debugging SELECT calls.
From the docs:
Statements that return a result set can be used within a stored procedure but not within a stored function. This prohibition includes SELECT statements that do not have an INTO var_list clause...
I arrived in search of answers to the same question, and found another way to work around the issue, so that I can use the SELECT statement that is the heart and soul of the MySQL function that elicited the warning.
Consider the following snippet.
SET intNMatches = ( SELECT COUNT(*) ...
SET coerces the SELECT statement to return its one and only column, a row count, into intNMatches, a local variable cast to BIGINT. Since it contains trade secrets, I can't show the rest of the query. Suffice it to say that the query installs without causing the MySQL engine to issue a warning.

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 ;