I am just trying to create a function which means to check if a table,function or view exists in a mysql database. But I get some errors in my database. Can someone help me out?
DELIMITER $$
DROP FUNCTION IF EXISTS check_if_exists$$
CREATE FUNCTION check_if_exists
(
object_name VARCHAR(100),
db_name VARCHAR(100),
object_type ENUM('t', 'f', 'v', 'p')
)
RETURNS INT
BEGIN
IF (object_type='t') THEN
SELECT COUNT(1) INTO @f_result
from information_schema.TABLES as t1
where t1.TABLE_SCHEMA=db_name
and t1.TABLE_NAME=object_name;
ELSE IF (object_type='f') THEN
select count(1) INTO @f_result
FROM information_schema.ROUTINES as info
WHERE info.ROUTINE_SCHEMA = db_name
AND info.ROUTINE_TYPE = 'FUNCTION' AND info.ROUTINE_NAME = object_name;
ELSE IF (object_type='v') THEN
select count(1) into @f_result
from information_schema.VIEWS as t1
where t1.TABLE_SCHEMA=db_name and t1.TABLE_NAME=object_name;
ELSE IF (object_type='p') THEN
SELECT COUNT(1) INTO @f_result
FROM information_schema.ROUTINES as info
WHERE info.ROUTINE_SCHEMA = db_name
AND info.ROUTINE_TYPE = 'PROCEDURE'
AND info.ROUTINE_NAME = object_name;
END IF;
return (@f_result);
END$$
delimiter ;
another thing, the info of mysql:
mysql Ver 14.14 Distrib 5.5.37, for Linux (x86_64) using readline 5.1
and the error message is:
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 31
as you see, the error message is not helpful. This definition of function do not depend any user database. So you can try in your own DBMS.
You start four
IF
statements, but you only have oneEND IF
at the end.The error message about syntax error near
''
indicates that it parsed to the end of the statement, expected to find more syntax (like the balancingEND IF
for the remaining nestedIF
statements), and didn't find it. The syntax error tries to give you context by showing you what text exists in the remaining part of the statement after the error, but if it reaches the end before it discovers the error, then there is no following text to report.You might consider using the CASE statement instead:
Re your comment:
Not in the way you were using. There is no "ladder" possible with an indefinite number of else-if clauses in standard SQL.
But many languages allow the else block to contain another if/then/else statement. So you can make complex branching code. But you have to terminate each if/then/else statement properly.
Languages that permit ladders:
elsif
)elsif
)elseif
)elif
)elseif
)elsif
)elsif
)elif
)Languages that do not permit ladders, but do permit nested control structures: