MySQL Workbench 6.2 create function - php

I'm trying to create a function in MySQL workbench, I have this SQL code:
DELIMITER $$
CREATE FUNCTION `regex_replace` (pattern VARCHAR(1000),replacement VARCHAR(1000),original VARCHAR(1000))
RETURNS VARCHAR(1000)
DETERMINISTIC
BEGIN
DECLARE temp VARCHAR(1000);
DECLARE ch VARCHAR(1);
DECLARE i INT;
SET i = 1;
SET temp = '';
IF original REGEXP pattern THEN
loop_label: LOOP
IF i>CHAR_LENGTH(original) THEN
LEAVE loop_label;
END IF;
SET ch = SUBSTRING(original,i,1);
IF NOT ch REGEXP pattern THEN
SET temp = CONCAT(temp,ch);
ELSE
SET temp = CONCAT(temp,replacement);
END IF;
SET i=i+1;
END LOOP;
ELSE
SET temp = original;
END IF;
RETURN temp;
END;
$$
DELIMITER ;
When I put this in phpMyAdmin, my function is created without any problems.
When I click on "Add Routine" in MySQL Workbench and then paste this code, I get this error:
Syntax error: 'DELIMITER' (identifier) is not valid input at this position
I'm no expert on MySQL functions, so I don't really know what to do with this. What is the problem here?
I really want to fix this, because MySQL Workbench now shows my function as _SYNTAX_ERROR instead of regex_replace.

When using the builtin procedure editor, MySQL Workbench adds a few extra commands:
USE `test`; // <----------
DROP procedure IF EXISTS `p2`; // <----------
DELIMITER $$
USE `test`$$ // <----------
CREATE PROCEDURE test.`p2` ()
LANGUAGE SQL
DETERMINISTIC
COMMENT 'Adds "nson" to first and last names in the record.'
BEGIN
SELECT 'Hello World';
END $$
DELIMITER ; // <----------
If you apply the above slashes to your procedure, it should help :)
For reference:
Stored Procedures Using MySQL Workbench

Related

Loop in phpmyadmin don't work

I try to make loop in MySQL, but it always shows me an error.
Is it correct code or did I make a mistake?
DROP PROCEDURE IF EXISTS proc_loop_test;
CREATE PROCEDURE proc_loop_test()
BEGIN
DECLARE int_val INT DEFAULT 0;
test_loop : LOOP
IF (int_val = 10) THEN
LEAVE test_loop;
END IF;
SET int_val = int_val +1;
SELECT int_val;
END LOOP;
END;
#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 '' at line 3
The problem is that the default delimiter is ; and stops the execution/parsing of the procedure code. Change the delimiter before you create the procedure and set it back to ; after the procedure code like this:
DROP PROCEDURE IF EXISTS proc_loop_test;
DELIMITER #
CREATE PROCEDURE proc_loop_test()
BEGIN
...
END #
DELIMITER ;

MySQL Stored Procedure that compares each row's date field and updates based on curdate()

This might be a noob question, but I tried googling about this issue and I haven't found any solution for it (I think). Anyway, I need to compare a date in a row from a mysql table to the current date and update the row depending on the results. I made a stored procedure that will be called by an event every x minutes. Here is my code for the sp:
delimiter //
CREATE PROCEDURE checkPromoValidity()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE id INT;
DECLARE lvn_status INT;
DECLARE lvn_validUntil DATE;
DECLARE cur1 CURSOR FOR SELECT promos.PROMO_NUMBER,promos.VALID_UNTIL,promos.status FROM MDCH_NEW.promos;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
open cur1;
check_loop: LOOP
fetch cur1 into id,lvn_validUntil,lvn_status;
IF done THEN
LEAVE check_loop;
END IF;
IF (lvn_validUntil > CURDATE()) THEN
update mdch_new.promos set MDCH_NEW.PROMOS.status = 0 where mdch_new.promos.PROMO_NUMBER = id;
END IF;
end LOOP;
close cur1;
END //
MDCH_NEW = database name
PROMOS= table name
EDIT: I CHANGED my delimiter to // just to see
edit2: added space after the final word, still getting the error below.. :(
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 '//' at line 23
delimiter $$
create procedure return7 ()
BEGIN
select 7;
END
$$
call return7();
you are free to re-use this code

Using a UDF MySQL query from PHP

I read from the MySQL doc
For the UDF mechanism to work, functions must be written in C or C++
and your operating system must support dynamic loading.
...
A UDF contains code that becomes part of the running server, so when
you write a UDF, you are bound by any and all constraints that apply
to writing server code
I want to create a MySQL function on the fly (by submitting it with PHP's mysqli) so that I can use it in a subsequent query.
Will I be unable to create a function on a basic web-hosting server's installation of MySQL (e.g. HostGator, 1and1, GoDaddy) since I'm not the root admin user?
What is wrong with my syntax in the below query? It doesn't work either in the direct MySQL shell (the black box) or through my php script. The error returned is:
Warning: mysqli::query() [mysqli.query]: (42000/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 'delimiter // create function IF NOT EXISTS LeaveNumber(str varchar(50)) retur' at line 1 in C:\wamp\www_quac\includes\database.php on line 55
This is my query in php:
if ($Database->query("
delimiter //
create function IF NOT EXISTS LeaveNumber(str varchar(50)) returns varchar(50)
no sql
begin
declare verification varchar(50);
declare result varchar(50) default '';
declare character varchar(2);
declare i integer default 1;
if char_length(str) > 0 then
while(i <= char_length(str)) do
set character = substring(str,i,1);
set verification = find_in_set(character,'1,2,3,4,5,6,7,8,9,0');
if verification > 0 then
set result = concat(result,character);
end if;
set i = i + 1;
end while;
return result;
else
return '';
end if;
end //
delimiter ;")) { echo 'hey the function was written. its called LeaveNumber()'; }
You have two syntax errors in your code:
create function does not support if exists
character is a reserved SQL keyword.
The below appears to work for me. I'd suggest using an SQL 'ide' such as MySQL workbench. It will show you syntax errors straight away.
DROP function IF EXISTS LeaveNumber;
delimiter //
create function LeaveNumber(str varchar(50)) returns varchar(50)
no sql
begin
declare verification varchar(50);
declare result varchar(50) default '';
declare nextChar varchar(2);
declare i integer default 1;
if char_length(str) > 0 then
while(i <= char_length(str)) do
set nextChar = substring(str,i,1);
set verification = find_in_set(nextChar,'1,2,3,4,5,6,7,8,9,0');
if verification > 0 then
set result = concat(result,nextChar);
end if;
set i = i + 1;
end while;
return result;
else
return '';
end if;
end //
delimiter ;

sql procedure import error

DELIMITER $$
drop procedure IF EXISTS `simpleproc`$$
CREATE PROCEDURE `simpleproc`(OUT param1 INT)
BEGIN
SELECT COUNT(*) INTO param1 FROM t;
END $$
DELIMITER ;
I am trying to import the above code using PHP but I'm getting this error:
Error performing query '':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 'DELIMITER $$ drop procedure IF EXISTS simpleproc$$ CREATE PROCEDURE `simplepro' at line 1
DELIMITER $$
DROP PROCEDURE IF EXISTS `simpleproc`$$
CREATE PROCEDURE `simpleproc`(OUT param1 INT)
READS SQL DATA
BEGIN
SELECT COUNT(*) INTO param1 FROM t;
END $$
DELIMITER ;$$
The above syntax can only be executable at MySQL command line client.
The same won't work using server side scripting language.
Instead you can use the following as a string to construct the query and pass to mysqli->query
CREATE PROCEDURE simpleproc (OUT param1 INT )
BEGIN
SELECT COUNT(*) INTO param1 FROM t;
END;
Note:
If you have only a single statement to be processed and executed in a stored procedure,
you don't even need begin - end blocks.
This is correct:
CREATE PROCEDURE simpleproc (OUT param1 INT )
SELECT COUNT(*) INTO param1 FROM t;
You have an error in your procedure syntax, please use following
DELIMITER $$;
DROP PROCEDURE IF EXISTS `simpleproc`$$
CREATE PROCEDURE `simpleproc` (OUT param1 INT)
BEGIN
SELECT COUNT(*) INTO param1 FROM t;
END$$
DELIMITER ;$$
This will solve your problem

Writing a MySql function within PHP

I have this following function in my php script:
$fcnsql = "CREATE FUNCTION CUST_ORDER(index INT, weekday INT, curweekday INT, endtime TIME, curtime TIME)
RETURNS INT
BEGIN
DECLARE custom_weekday INT;
IF (weekday=curweekday AND curtime>endtime) THEN
SET custom_weekday = index+7;
ELSE
SET custom_weekday = index;
END IF;
RETURN custom_weekday;
END";
$test=mysql_query($fcnsql) or die (mysql_error());
What I get as output is that I have a SQL syntax error. Any idea what is wrong?
Some things I think could be the problem:
I'm not sure if its the correct syntax for having TIME variables as parameters in my function.
I see on some sample code online that before a mysql function, there is a line "delimiter $$"--I'm not sure what this is for and how/whether I need to use it.
I'm very new to this, so any help would be greatly appreciated!
EDIT: #Pang called it - index is a reserved word. If you don't want to change the name, then wrap it in backticks:
`index`
I'll keep the rest of my waffle in place, as you weren't sure about DELIMITER. :)
--
The error is probably that you haven't set the DELIMITER, as you noticed in some examples. Add these to the top and bottom of your function:
$fcnsql = "
DELIMITER #
CREATE FUNCTION CUST_ORDER2(`index` INT, weekday INT, curweekday INT, endtime TIME, curtime TIME) RETURNS INT
BEGIN
DECLARE custom_weekday INT;
IF (weekday=curweekday AND curtime>endtime) THEN
SET custom_weekday = `index`+7;
ELSE
SET custom_weekday = `index`;
END IF;
RETURN custom_weekday;
END;
#
DELIMITER ;
";
The reason is that ";" is MySQLs default delimiter (i.e. the thing that tells MySQL it has hit the end of a statement). Your function's statements needs delimiters, but whilst MySQL is saving it, you don't want MySQL to think it's found the end of a statement and stop processing the function. So you change the delimiter to a character that you aren't using in the function, then change it back again afterwards.

Categories