Stored Procedures Using MySQL Workbench - mysql

Very new to the environment, I have a question about a line that's added to the end of my code. The guide I'm following is:
http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/
If anyone has a better one regarding MySQL stored procedures, I'm all ears.
Before I ask, this is the environment I'm using:
OS: Windows 7 / WAMP (MySQL 5.5.24) / MySQL Workbench
I'm instructed to define a delimiter; in my case I'm sticking with the default '$$.'
The stored procedure I created is:
DELIMITER $$
CREATE PROCEDURE test.`p2` ()
LANGUAGE SQL
DETERMINISTIC
COMMENT 'Adds "nson" to first and last names in the record.'
BEGIN
SELECT 'Hello World';
END $$
When I apply this stored procedure and I get the review screen, I see a new line of code added;
At the bottom:
DELIMITER ;
This lats line; is it added because the DELIMITER statement announces a block within which the defined delimiters ($$) can be used and thus closes the block in the end?

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 ; // <----------
Those commands are not strictly related to the stored procedures syntax, they're merely a commodity—other MySQL clients (such as HeidiSQL or the official command line utility) will not add them. The last delimiter change is probably a reset to avoid problems in future statements on the same connection.
You need to change the delimiter in order to instruct the client about where the procedure code starts and end. The problem is that the procedure body is normally a collection of SQL statements so omitting the delimiter change would make MySQL think that you are attempting to run a series of statements, the first of which would be this:
CREATE PROCEDURE test.`p2` ()
LANGUAGE SQL
DETERMINISTIC
COMMENT 'Adds "nson" to first and last names in the record.'
BEGIN
SELECT 'Hello World';
With DELIMITER $$ you are telling MySQL that your full statement goes from CREATE to END. It's just syntactic sugar: DELIMITER is not even a SQL keyword. HeidiSQL, for instance, provides a GUI with a text box where you write the procedure body, thus you don't need the DELIMITER workaround.

Related

How to write pl/sql or equivalent of it, in MySQL Workbench?

CREATE PROCEDURE `new_procedure` ()
declare v int;
BEGIN
v := 10;
dbms_output.put_line(v);
END
Here I was writing this simple code in create procedure portion and getting error in MySQL Workbench.
This is how you create a stored procedure in MySQL from Workbench:
DELIMITER //
CREATE PROCEDURE MyStoredProcedure
(IN colValue CHAR(20))
BEGIN
INSERT INTO MyTable(MyColumn) VALUES(colValue);
END //
DELIMITER ;
You can read more about it in the MySQL Documentation.
To execute the procedure: CALL MyStoredProcedure(<some_value>);
Stored procedures were introduced in MySQL 5 so be sure to be running that version.
Why do we need to temporarily change the DELIMITER?
From the doc:
By default, mysql itself recognizes the semicolon as a statement
delimiter, so you must redefine the delimiter temporarily to cause
mysql to pass the entire stored program definition to the server. To
redefine the mysql delimiter, use the delimiter command.

MySQL unable to understand the syntax error [duplicate]

Very new to the environment, I have a question about a line that's added to the end of my code. The guide I'm following is:
http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/
If anyone has a better one regarding MySQL stored procedures, I'm all ears.
Before I ask, this is the environment I'm using:
OS: Windows 7 / WAMP (MySQL 5.5.24) / MySQL Workbench
I'm instructed to define a delimiter; in my case I'm sticking with the default '$$.'
The stored procedure I created is:
DELIMITER $$
CREATE PROCEDURE test.`p2` ()
LANGUAGE SQL
DETERMINISTIC
COMMENT 'Adds "nson" to first and last names in the record.'
BEGIN
SELECT 'Hello World';
END $$
When I apply this stored procedure and I get the review screen, I see a new line of code added;
At the bottom:
DELIMITER ;
This lats line; is it added because the DELIMITER statement announces a block within which the defined delimiters ($$) can be used and thus closes the block in the end?
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 ; // <----------
Those commands are not strictly related to the stored procedures syntax, they're merely a commodity—other MySQL clients (such as HeidiSQL or the official command line utility) will not add them. The last delimiter change is probably a reset to avoid problems in future statements on the same connection.
You need to change the delimiter in order to instruct the client about where the procedure code starts and end. The problem is that the procedure body is normally a collection of SQL statements so omitting the delimiter change would make MySQL think that you are attempting to run a series of statements, the first of which would be this:
CREATE PROCEDURE test.`p2` ()
LANGUAGE SQL
DETERMINISTIC
COMMENT 'Adds "nson" to first and last names in the record.'
BEGIN
SELECT 'Hello World';
With DELIMITER $$ you are telling MySQL that your full statement goes from CREATE to END. It's just syntactic sugar: DELIMITER is not even a SQL keyword. HeidiSQL, for instance, provides a GUI with a text box where you write the procedure body, thus you don't need the DELIMITER workaround.

Yet another MySQL syntax error

This isn't something I usually have problems with but I don't understand that one now. I tried with backticks, with double quotes, without backticks,...
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 7
CREATE PROCEDURE mapping(
p_object INT(10),
brand VARCHAR(255),
model VARCHAR(255))
BEGIN
INSERT INTO `object_brand_model_mapping`
SET `object`=p_object, `brandNameNormalized`=brand, `modelNameNormalized`=model;
END;
I also tried
INSERT INTO `object_brand_model_mapping`
(`object`, `brandNameNormalized`, `modelNameNormalized`)
VALUES
(p_object, brand, model);
which produces exactly the same error.
I don't know what's wrong with this. Do any special rules apply to INSERT in a procedure?
All of the columns do exist.
The parser is getting confused by having a common delimiter between defining the procedure and the procedure contents. To remedy this, define a different delimiter before creating the procedure:
DELIMITER $$
CREATE PROCEDURE mapping(
p_object INT(10),
brand VARCHAR(255),
model VARCHAR(255))
BEGIN
INSERT INTO `object_brand_model_mapping` (`object`, `brandNameNormalized`, `modelNameNormalized`)
VALUES (p_object, brand, model);
END$$
DELIMITER ;
From Alex Silverstein's article on the subject:
The next step is to change the default MySQL script parser’s delimiter from semicolon (;) to double-dollar sign ($$). The reason you do this is so that the semicolons after each statement in the body of the routine are not interpreted by the parser as meaning the end of the CREATE PROCEDURE statement. This is because the entire CREATE PROCEDURE block, from CREATE PROCEDURE to END is actually a single statement that must be executed by itself. Were it not for the delimiter change, the script would break, since there each statement inside BEGIN and END would execute individually. Note that you can use a variety of non-reserved characters to make your own custom delimiter.

Delimiters in MySQL

I often see people are using Delimiters. I tried myself to find out what are delimiters and what is their purpose. After 20 minutes of googling, I was not able to find an answer which satisfies me. So, my question is now: What are delimiters and when should I use them?
Delimiters other than the default ; are typically used when defining functions, stored procedures, and triggers wherein you must define multiple statements. You define a different delimiter like $$ which is used to define the end of the entire procedure, but inside it, individual statements are each terminated by ;. That way, when the code is run in the mysql client, the client can tell where the entire procedure ends and execute it as a unit rather than executing the individual statements inside.
Note that the DELIMITER keyword is a function of the command line mysql client (and some other clients) only and not a regular MySQL language feature. It won't work if you tried to pass it through a programming language API to MySQL. Some other clients like PHPMyAdmin have other methods to specify a non-default delimiter.
Example:
DELIMITER $$
/* This is a complete statement, not part of the procedure, so use the custom delimiter $$ */
DROP PROCEDURE my_procedure$$
/* Now start the procedure code */
CREATE PROCEDURE my_procedure ()
BEGIN
/* Inside the procedure, individual statements terminate with ; */
CREATE TABLE tablea (
col1 INT,
col2 INT
);
INSERT INTO tablea
SELECT * FROM table1;
CREATE TABLE tableb (
col1 INT,
col2 INT
);
INSERT INTO tableb
SELECT * FROM table2;
/* whole procedure ends with the custom delimiter */
END$$
/* Finally, reset the delimiter to the default ; */
DELIMITER ;
Attempting to use DELIMITER with a client that doesn't support it will cause it to be sent to the server, which will report a syntax error. For example, using PHP and MySQLi:
$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$result = $mysqli->query('DELIMITER $$');
echo $mysqli->error;
Errors with:
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 $$' at line 1
The DELIMITER statement changes the standard delimiter which is semicolon ( ;) to another. The delimiter is changed from the semicolon( ;) to double-slashes //.
Why do we have to change the delimiter?
Because we want to pass the stored procedure, custom functions etc. to the server as a whole rather than letting mysql tool to interpret each statement at a time.
When you create a stored routine that has a BEGIN...END block, statements within the block are terminated by semicolon (;). But the CREATE PROCEDURE statement also needs a terminator. So it becomes ambiguous whether the semicolon within the body of the routine terminates CREATE PROCEDURE, or terminates one of the statements within the body of the procedure.
The way to resolve the ambiguity is to declare a distinct string (which must not occur within the body of the procedure) that the MySQL client recognizes as the true terminator for the CREATE PROCEDURE statement.
You define a DELIMITER to tell the mysql client to treat the statements, functions, stored procedures or triggers as an entire statement. Normally in a .sql file you set a different DELIMITER like $$. The DELIMITER command is used to change the standard delimiter of MySQL commands (i.e. ;). As the statements within the routines (functions, stored procedures or triggers) end with a semi-colon (;), to treat them as a compound statement
we use DELIMITER. If not defined when using different routines in the same file or command line, it will give syntax error.
Note that you can use a variety of non-reserved characters to make your own custom delimiter. You should avoid the use of the backslash (\) character because that is the escape character for MySQL.
DELIMITER isn't really a MySQL language command, it's a client command.
Example
DELIMITER $$
/*This is treated as a single statement as it ends with $$ */
DROP PROCEDURE IF EXISTS `get_count_for_department`$$
/*This routine is a compound statement. It ends with $$ to let the mysql client know to execute it as a single statement.*/
CREATE DEFINER=`student`#`localhost` PROCEDURE `get_count_for_department`(IN the_department VARCHAR(64), OUT the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count FROM employees where department=the_department;
END$$
/*DELIMITER is set to it's default*/
DELIMITER ;

create procedure fails?

when trying to create a simple procedure in mysql 5.1.47-community it fails everytime i've tried everything!
even simple things like this!
DELIMITER //
CREATE PROCEDURE two ()
begin
SELECT 1+1;
end;
//
The error is
ERROR: Error 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 'mydb' at line 1
The error message you've given doesn't correspond to the code you've pasted. You're referring to "mydb" somewhere in the SQL you're running yet it's not anywhere in the code you've put in the question.
The code you've given should work fine as I see no syntax errors, you may just need to give it a database to work on ("test" in my case here, perhaps it should be "mydb" for you?).
DELIMITER //
CREATE PROCEDURE test.two ()
begin
SELECT 1+1;
end;
//
DELIMITER ;
CALL test.two;
However, I suspect the error you're getting is become of a line in your SQL that you're not showing us.
EDIT
It could perhaps be the delimiter command. You're changing the delimiter to // rather than the default ;. So perhaps you've run that command (and changed the delimiter for your session to //), and then tried to run USE mydb; where the ; is no longer recognised as a valid delimiter for your session, and that could be giving you the error. Try putting delimiter ; before your use line and see if that helps (and then use it again after you've defined your stored procedure so you can call it). This is just a theory though, as I'm not sure of the intricacies of the delimiter command.
Remove the final delimiter "end" instead "end;"
I had the same problem using heidisql as the fronted to enter the SQL. My first attempt was:
CREATE PROCEDURE Add_Two (IN someNumber int, OUT result INT)
BEGIN
SELECT someNumber +2 INTO result;
END
and this resulted in SQL ERROR (1064) because i was not aware that when using a client program a delimiter is needed to define the stored procedures.
After changing the above to this:
DELIMITER //
CREATE PROCEDURE Add_Two(IN someNumber int, OUT result INT)
BEGIN
SELECT someNumber +2 INTO result;
END
//
It worked out.
Example to call it
SET #someNumber :=8;
CALL Add_Two(#someNumber, #result);
SELECT #result;