How to insert the SQL Error message into table - mysql

I want to store the error messages which occurs while executing the stored procedure in another error table.
Here is the my sample procedure having some error statements.
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`$$
CREATE PROCEDURE `test`()
BEGIN
SELECT * FROM emp;
END $$
DELIMITER $$;
When i call the above procedure it gives me error.I wnat to store this error code & message in another table as "error".
Any pointers are appreciated.
Thanks in Advance.

The standard way to handle this in MySQL is to declare a HANDLER to handle the error condition the way you want. This allows you to insert an error message into another table if you want, and then to either CONTINUE or EXIT the running procedure as required.
Here's the documentation:
http://dev.mysql.com/doc/refman/5.0/en/declare-handler.html
Unfortunately you will not be able to access the SQLSTATE of the statement that caused the error, so this approach is somewhat limited.
Here's another relevant question on SO with much more detail:
MySQL Stored Procedure Error Handling

SQL ERROR means there is something wrong with your SQL Query. It may (or may not) depend on your table. If the error is TABLE SPECIFIC or QUERY SYNTAX ERROR, that is, if there is something wrong with a specific table ONLY, or with a query, then definitely you can insert your errors into a table. But, if there is something with your CONNECTION or something else, then you cannot insert errors into any table.
ALWAYS try to log your errors in a html file or txt (text) file, so that you can smoothly access it. Also there is a less chance for failure.

Related

Run stored procedure included sql script using robot framework

I want to run sql script which include db and table creations and stored procedure creations.
but when I try to run sql script using execute sql script keyword in database library I get an error like below
ProgrammingError: (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 'DELIMITER $$\n CREATE OR
REPLACE PROCEDURE `proc_GetCustomerDetails`(\n I...' at line 2")
before procedure I have delimiter like this,
DELIMITER $$
CREATE OR REPLACE PROCEDURE `proc_GetCustomerDetails`(
IN CustomerNbr LONGTEXT,
IN Lang VARCHAR(5)
)
DETERMINISTIC
BEGIN
IF Lang IS NULL THEN SET lang = "fin";
END IF;
SELECT * from dbname.customer;
END;$$
DELIMITER ;
If I comment stored procedure part, sql file is running without errors with rest of the table creation statements.
I googled this and couldn't find any related issue. I saw we have call stored procedure keyword. but I want to keep table creations and stored procedures in same sql file and need to run. I use MariaDB for this task.
Libraries used,
pymysql
robotframework-databaselibrary
If I run sql file using HeidiSQL it is running without any errors with procedures and delimiters. That mean there are no sql errors.
Can Someone tell me how to fix this?
DELIMITER is a statement supported only for the client, it is not supported by the server; thus the error. The solution - drop it.
Here's a question with very good answers what is it and why it's needed.
In short - when you work with a client you need a way to instruct it "this is not a statement you should execute immediately, this is still just a line in the SP you'll be sending to the server" - so you tell (to the client) "the DELIMITER b/n statements is temporarily $$". The server doesn't need/care about that - it knows everything between CREATE PROCEDURE, BEGIN, END are connected statements, a block.
When you connect to the DB through API (pymysql) vs an interactive client (shell, heidisql, etc) - you're sending the SP as a block, there's no way its statements will be ran one by one, thus the DELIMITER is not needed, not a supported command by the server, and generates an error. Drop it.

SQL error when I try to ALTER TABLE in a stored procedure

I have a stored procedure designed to generate a new, 'derived' table. In this procedure I then want to add a column using ALTER TABLE. However, despite an almost identical stored procedure working fine, and despite being able to add this manually as a stored procedure to the database using MySQL Workbench, when I pass the code to the server using SOURCE (i.e. SOURCE workload.sql), I get an error 1146 (42502) 'Table 'workload._convenor_workload' doesn't exist.' (I'm doing this in Emacs as part of a org-babel block, but this is essentially just passing raw SQL to the server.)
As background, I'm in the process of migrating SQL code from a setting where I was running it raw to create my final database to one where I'd like this code to be called via triggers.
Setup: mysql Ver 8.0.16 for macos10.14 on x86_64 (MySQL Community Server - GPL)
I've tried rewriting this as a prepared statement, was unsuccessful, and have been scouring Stack Overflow. This is my first MySQL project and my reading of the documentation suggests that ALTER TABLE is a perfectly legal thing to do in a stored procedure. It's likely that I'm making a schoolboy error somewhere but at the moment I'm banging my head.
Elsewhere in my SQL, this code works in a stored procedure (ALTER TABLE function does not throw an error):
CREATE TABLE _assessment_allocations AS SELECT Assessment_ID,
IFNULL(SUM(_total_first_marking_hours),0) AS _total_first_marking_hours_sum,
GROUP_CONCAT(DISTINCT _total_first_marking_hours_needed) AS _total_first_marking_hours_needed,
GROUP_CONCAT(DISTINCT Prog_ID) AS prog_id
FROM
_marking_workload
GROUP BY Prog_ID, Assessment_ID;
ALTER TABLE _assessment_allocations
ADD COLUMN _assessment_variance DECIMAL(5,2);
However, the code that throws the error is this (specifically, the ALTER TABLE function; I've added the stored procedure code in case this is helpful). Note that this code does not throw an error when ingested by MySQL outside a stored procedure:
USE `workload`;
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `module_administration_convenor`()
-- Begin by selecting elements of the ~modules~ table
CREATE TABLE `_convenor_workload` AS
SELECT Modules.Module_Code,
Modules.Module_Name,
Modules.Module_Convenor_ID,
Modules.Module_Convenor_Share,
Modules.Student_Tally,
Modules.Additional_Hours,
Modules.Convening_Notes,
Modules.Active_Status
FROM modules;
-- Add a 'Convenor' column
ALTER TABLE `_convenor_workload` ADD COLUMN `Name` VARCHAR(255) DEFAULT 'Convenor';
\* Other stuff *\
END$$
DELIMITER ;
My aim is to avoid throwing this error. I'd like to get this stored procedure actually stored! (Just like the previous stored procedure that does much the same and does not throw an error.) I'm aware that there are some back-tick and style differences between the working and non-working code, but I'm guessing these aren't super important.
As I said, I have a strong suspicion that I'm overlooking something obvious here...
As mentioned by Solarflare in the comments, you are missing a begin so the alter table is executing as a separate action. If you wrap it with begin and end then it treats all the code as the stored procedure.
USE `workload`;
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `module_administration_convenor`()
Begin
-- Begin by selecting elements of the ~modules~ table
CREATE TABLE `_convenor_workload` AS
SELECT Modules.Module_Code,
Modules.Module_Name,
Modules.Module_Convenor_ID,
Modules.Module_Convenor_Share,
Modules.Student_Tally,
Modules.Additional_Hours,
Modules.Convening_Notes,
Modules.Active_Status
FROM modules;
-- Add a 'Convenor' column
ALTER TABLE `_convenor_workload` ADD COLUMN `Name` VARCHAR(255) DEFAULT 'Convenor';
END
$$
DELIMITER ;

Call a stored procedure from within a view

I have a procedure that creates a table, is it possible to have a view (or similar) that can call the procedure then select from the table?
I've tried this:
DELIMITER $$
CREATE DEFINER=`root`#`localhost` FUNCTION `new_routine`(p1 INT) RETURNS int(1)
BEGIN
CALL rMergeDateFields();
RETURN 1;
END
CREATE VIEW `db`.`vIntervals` AS
SELECT new_routine(0) AS col1;
SELECT * FROM MergedData;
but I get this error
Error 1422: Explicit or implicit commit is not allowed in stored function or trigger.
Any ideas?
No, you cannot. Views are typically read-only operations; and that behavior cannot be guaranteed if stored-procedures are invoked.
Related question:
How to call Stored Procedure in a View?
Is it possible to call stored procedure in view?
Here is a canonical resource:
http://dev.mysql.com/doc/refman/5.1/en/view-updatability.html
Some views are updatable. That is, you can use them in statements such as UPDATE, DELETE, or INSERT to update the contents of the underlying table. For a view to be updatable, there must be a one-to-one relationship between the rows in the view and the rows in the underlying table. There are also certain other constructs that make a view nonupdatable.
As invoking the stored procedure cannot assure 1:1 relationships with view rows, the update is not permitted.
You can't do this from a view, but a stored procedure itself can return a result set.
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `merge_and_select` ()
BEGIN
CALL rMergeDateFields();
SELECT * FROM MergeData;
END $$
If you CALL merge_and_select() the rMergeDateFields procedure will be run and then you will get the contents of the MergeData table returned to you, in one step... which sounds like what you're wanting.
This is, however, a really bad implementation, because there's no control for concurrent calls to merge_and_select(), so all kinds of things could go wrong if it's run more than once at the same time.
However, depending on what you really need rMergeDateFields() to do, it's possible that you could rewrite rMergeDateFields() to actually perform whatever work you need done and return it directly to the client without using the MergeData table using an unbounded SELECT, as shown above.
Anything you SELECT in a stored procedure without using INTO a variable is returned to the client as a response from the CALL.

MYSQL 5.5 Nested Stored Procedure Error Handling

I'm using MYSQL 5.5, How to do Error Handling with Nested Stored Procedure. Pretty much most of the stored procedure, does truncate table, insert into select * from and insert into on duplicate key update.
If there is any issue with any of the nested stored procedure, I would like to catch that error or tell me that error happened in that particular stored procedure.
Right now, due to the nested stored procedure, there is no way for me to know,
in which stored procedure, the exception happended.
Within each stored procedure, you can DECLARE ... HANDLER for the errors in which you're interested and have them write state information to a temporary table; that table can subsequently be read by other (outer) stored procedures to determine what error(s), if any, were raised.

Trouble creating stored procedure

I'm messing around with stored procedures for the first time, but can't even create a simple select! I'm using phpMyAdmin and this is my SQL:
DELIMITER //
CREATE PROCEDURE test_select()
BEGIN
SELECT * FROM products LIMIT 10;
END //
DELIMITER ;
After submitting that, my localhost does some thinking for a loooong time and eventually loads a page with no content called /phpmyadmin/import.php. After reloading phpMyAdmin and trying to invoke the procedure:
CALL test_select();
I get a "PROCEDURE doesn't exist" error. Any ideas?
Try to use the delimiter field of phpMyAdmin, as shown in the screenshot below:
Simply put the following in the query window:
CREATE PROCEDURE test_select()
BEGIN
SELECT * FROM products LIMIT 10;
END
In addition note that there is bug in some older versions of phpMyAdmin, which can cause an error when you call stored procedures that contain SELECT statements from phpMyAdmin.
You may want to check out the following posts for further reading:
MySQL Stored Procedures not working with SELECT (basic question)
How do I write an SP in phpMyAdmin (MySQL)?
This bug effects only phpMyAdmin, and you would still be able to call the stored procedure from anywhere else.