MySQL Stored Procedures - mysql

I'm coming from a MS SQL Server background.
Working on a new project using MySQL with NaviCat 8 Admin tools.
Ok, here's the question.
Normally when working in MS land if I want to update some data I use a stored procedure to do this:
Drop Procedure spNew
Create Procedure spNew (#P_Param)
UPDATE Table
SET Field = 'some value'
WHERE ID = #P_Param
I am trying to do this same logic from within NaviCat.
I defined the Parameter, (IN '#P_Param' int)
In the Definition i placed:
BEGIN
UPDATE Table
SET Field = 'some value'
WHERE ID = #P_Param
END;
When I try and save the stored procedure, i'm getting this error:
"1064 - You have an error in your SQL syntax, blah, blah, blah"
Can anyone at least point me in the right direction?
Thanks.

CREATE PROCEDURE spNew(P_Param INT)
BEGIN
UPDATE Table
SET Field = 'some value'
WHERE ID = P_Param;
END;
Note that MySQL syntax and overall ideology are very different from those of SQL Server.
You may also need to set delimiter:
DELIMITER $$
CREATE PROCEDURE spNew(P_Param INT)
BEGIN
UPDATE Table
SET Field = 'some value'
WHERE ID = P_Param;
END;
$$
DELIMITER ;
BTW, I'm assuming you don't actually call your table "Table", since it's a reserved word.
If you do, you need to enclose it into backticks like this:
DELIMITER $$
CREATE PROCEDURE spNew(P_Param INT)
BEGIN
UPDATE `Table`
SET `Field` = 'some value'
WHERE `ID` = P_Param;
END;
$$
DELIMITER ;

Parameters to MySQL stored procedures aren't prefixed with # or quoted in either the declaration or when used. Local variables are prefixed with #, however.
Try:
DROP PROCEDURE IF EXISTS spNew;
CREATE PROCEDURE spNew(IN P_Param INT)
BEGIN
UPDATE Table
SET Field = 'some value'
WHERE ID = P_Param
END;

Related

Translate a Merge statement used in sql server in Mysql

Please support, I had a stored procedure create in sql server database using a Merge statement inside. I would like to use the same stored procedure in a Mysql database. Unfortunatly it seem the Merge funtion not work in MySql. Anybody can help me to do that ? Below my stored procedure
ALTER PROCEDURE [dbo].[ValiderFacturePharmacie]
#numdossierhospi VARCHAR(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
MERGE INTO pharmacie P
USING (SELECT NumDossHp, SUM(TotalProd) AS Total
FROM pharmacie WHERE NumDossHp = #numdossierhospi
GROUP BY NumDossHp) T
ON (P.NumDossHp = T.NumDossHp)
WHEN MATCHED THEN
UPDATE SET
P.TotalPharma = T.Total,
P.Etat ='VALIDE';
END
Thanks you for your answer ! I solved the issue by using this statement below
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `ValiderFacturePharmacie`(IN `numdossierhospi` VARCHAR(30))
NO SQL
UPDATE pharmacies
SET totalpharma = (select SUM(totalprod) from pharmacies where numdosshp = numdossierhospi),
etat = 'FACTURER'
WHERE numdosshp = numdossierhospi$$
DELIMITER ;
It is alomst the same
DELIMITER //
CREATE PROCEDURE ValiderFacturePharmacie (
_numdossierhospi VARCHAR(50))
BEGIN
UPDATE pharmacie P INNER JOIN
(SELECT NumDossHp, SUM(TotalProd) AS Total
FROM pharmacie WHERE NumDossHp = _numdossierhospi
GROUP BY NumDossHp) T
ON (P.NumDossHp = T.NumDossHp)
SET
P.TotalPharma = T.Total,
P.Etat ='VALIDE';
END //
DELIMITER ;

Stored procedure to create a MaillingListCount

I am following sql in 10 minutes to learn "stored procedure"
#+BEGIN_SRC sql :engine mysql :dbuser org :database grocer
CREATE PROCEDURE MailingListCount (
ListCount OUT INTEGER )
IS
v_rows INTEGER;
BEGIN
SELECT COUNT(*) INTO v_rows
FROM Customers
WHERE NOT cust_email IS NULL;
ListCount := v_rows;
END;
#+END_SRC
#+RESULTS:
| |
it report error:
ERROR 1064 (42000) at line 1: 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 'OUT INTEGER )
IS
v_rows INTEGER' at line 2
Could you please provide any hints?
Couple of fixes:
The OUT comes before the parameter name
Remove the unnecessary IS
Declare the variables inside the BEGIN END block
Use SET when you assign variables
So:
CREATE PROCEDURE MailingListCount(OUT ListCount INTEGER )
BEGIN
declare v_rows INTEGER;
SELECT COUNT(*) INTO v_rows
FROM Customers
WHERE NOT cust_email IS NULL;
SET ListCount := v_rows;
END;
Usually it's easier to handle the procedure output from result set rather than OUT variables. The OUT variables are useful primarily on calls between procedures.
So if you plan to call the routine from application, use:
CREATE PROCEDURE MailingListCount()
BEGIN
SELECT COUNT(*) as 'Count'
FROM Customers
WHERE NOT cust_email IS NULL;
END;
First thing is the position of the OUT keyword. It should be before the Parameter name.
Then second one no need to create the variable v_rows to store the output and then finally assigning it back to the OUT parameter listCount.
If you want to check condition like email should not null then you should do something like WHERE cust_email IS NOT NULL instead of WHERE NOT cust_email IS NULL
Please refer below code for the reference :
DELIMITER $$
CREATE PROCEDURE `MailingListCount` (OUT listCount INTEGER)
BEGIN
SELECT COUNT(*) INTO listCount
FROM Customers
WHERE cust_email IS NOT NULL;
END$$
DELIMITER ;
You can use the different delimiter for the MySql stored procedures and functions.
MySql use ; as default delimiter so 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.
You can refer the https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html to learn MySQL Stored procedure.

MySQL stored procedure # syntax error

I want to be able to pass arguments to stored procedure, so I searched the net and encountered something like this:
DELIMITER $$
CREATE PROCEDURE addTmpUser
#id varchar(10)
AS
BEGIN
//some sql code
END$$
DELIMITER ;
The problem is that I am getting a syntax error for the # character.
Note: I am using MySQL db.
You are mixing variable types.
#variable is a user variable with a scope for the entire connection.
The variables in stored procedures look different, they don't have the # before them.
Also, you need to declare them. Here is an example
DELIMITER $$
CREATE PROCEDURE addTmpUser(p_id varchar(10))
-- the variable is named p_id as a nameing convention.
-- It is easy for variables to be mixed up with column names otherwise.
BEGIN
DECLARE innerVariable int;
insert into user (id) values (p_id);
-- return all users
select * from user;
END$$
DELIMITER ;
-- and now call it
call addTmpUser(10);
You need to use IN,OUT,INOUT to specify the parameter. So you can try this
DELIMITER $$
CREATE PROCEDURE addTmpUser (IN id VARCHAR(10))
BEGIN
//some sql code
END$$
DELIMITER ;
Look at the documentation

How to Alter a stored procedure in mysql

How to Alter a stored procedure in Mysql.
DROP PROCEDURE IF EXISTS sp_Country_UPDATE;
CREATE PROCEDURE sp_Country_UPDATE
( IN p_CountryId int,
IN p_CountryName nvarchar(25),
IN p_CountryDescription nvarchar(25),
IN p_IsActive bit,
IN p_IsDeleted bit )
UPDATE
Country
SET
CountryName = p_CountryName ,
CountryDescription=p_CountryDescription,
IsActive= p_IsActive,
IsDeleted=p_IsDeleted
WHERE
CountryId = p_CountryId ;
How to alter this Stored Procedure?
If you mean you want to edit the Procedure, then you can't according to the MySQL docs:
This statement can be used to change the characteristics of a stored procedure. More than one change may be specified in an ALTER PROCEDURE statement. However, you cannot change the parameters or body of a stored procedure using this statement; to make such changes, you must drop and re-create the procedure using DROP PROCEDURE and CREATE PROCEDURE.
The Alter syntax lets you change the "characteristics" but not the actual procedure itself
http://dev.mysql.com/doc/refman/5.0/en/alter-procedure.html
Here's an example of creating, Altering (the comment) then dropping and recreating:
DROP PROCEDURE myFunc;
DELIMITER //
CREATE PROCEDURE myFunc ()
COMMENT 'test'
BEGIN
SELECT 5;
END //
DELIMITER ;
ALTER PROCEDURE myFunc
COMMENT 'new comment';
CALL myFunc();
DROP PROCEDURE myFunc;
DELIMITER //
CREATE PROCEDURE myFunc ()
COMMENT 'last time'
BEGIN
SELECT 6;
END //
DELIMITER ;
CALL myFunc();
The above CALL myFunc() statments would return 5 and then 6.
Viewing the stored procedure would show a comment of "test", "new comment" or "last time" depending on when you viewed the Procedure body (I'm not sure how to view the comments via the CLI but I can see them in the functions tab in Navicat)
ALTER PROCEDURE proc_name [characteristic ...]
characteristic:
COMMENT 'string'
| LANGUAGE SQL
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
This is how you Create
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
This is how you Alter
Alter PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //

Creating a procedure in mySql with parameters

I am trying to make a stored procedure using mySQL. This procedure will validate a username and a password. I'm currently running mySQL 5.0.32 so it should be possible to create procedures.
Heres the code I've used. All I get is an SQL syntax error.
GO
CREATE PROCEDURE checkUser
(IN #brugernavn varchar(64)),IN #password varchar(64))
BEGIN
SELECT COUNT(*) FROM bruger WHERE bruger.brugernavn=#brugernavn AND bruger.pass=#Password;
END;
Thank you in advance
I figured it out now. Here's the correct answer
CREATE PROCEDURE checkUser
(
brugernavn1 varchar(64),
password varchar(64)
)
BEGIN
SELECT COUNT(*) FROM bruger
WHERE bruger.brugernavn=brugernavn1
AND bruger.pass=password;
END;
# points to a global var in mysql. The above syntax is correct.
(IN #brugernavn varchar(64)**)**,IN #password varchar(64))
The problem is the )
Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.
DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;
In the above example ,database and table names are student_database and student respectively.
Note: Instead of s_name, you can also pass #s_name as global variable.
How to call procedure?
Well! its very easy, simply you can call procedure by hitting this command
$mysql> CAll getStudentInfo('pass_required_name');