Mysql procedure sum - mysql

I cannot remember how to do a basic SUM in a SQL proceedure, can anybody remind me quickly please?
drop procedure if exists pCaCalculateCcyFluc;
delimiter //
create procedure pCaCalculateCcyFluc(
IN pPrice DECIMAL(10,6),
IN pPricePrev DECIMAL(10,6),
OUT pCcyFluc DECIMAL(10,6)
)
MODIFIES SQL DATA
COMMENT 'calculate fluctuation'
begin
pCcyFluc = (pPricePrev - pPrice)/pPrice;
--
end;
//
delimiter ;

To use the SUM Function:
SELECT SUM(TableName.ColumnName)
FROM TableName
JOIN TableName ON TableName.ColumnName = TableName.ColumnName
GROUP BY TableName.ColumnName;
Check out these examples.

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 ;

MySQL Stored Procedure - IF EXISTS ... THEN returning unexpected result

The below is my Stored Procedure(Routine) to check whether or not a user with Username(input) exists in the database.
Inside the database, I already have a user with Username - 'dev'.
However, when I ran the below routine, it returned me with res = 1, which I expected it to be -1.
I called the routine this way. Please correct me too if I am calling it the wrong way. I am really new to MySQL Routines.
CALL usp_GetUserValidation ('dev', #ErrorCode)
Can any MySQL Routine pros here enlighten me on this? Thank you in advance guys :)
DELIMITER $$
CREATE PROCEDURE usp_GetUserValidation(IN `#Username` VARCHAR(255), OUT `#ErrorCode` INT)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'To validate user login'
BEGIN
IF EXISTS
(SELECT UserID
FROM mt_User
WHERE UserName = #Username)
THEN
SET #ErrorCode = -1;
ELSE
SET #ErrorCode = 1;
END IF;
SELECT #ErrorCode AS res;
END$$
DELIMITER ;
It was simply your naming conventions for the parameters. It is finicky and does not like User Variable # signs in them.
You are just testing I can see, as you are returning both a resultset with the info and the OUT variable.
drop procedure if exists usp_GetUserValidation;
DELIMITER $$
CREATE PROCEDURE usp_GetUserValidation(IN pUsername VARCHAR(255), OUT pErrorCode INT)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'To validate user login'
BEGIN
IF EXISTS
(SELECT UserID
FROM mt_User
WHERE UserName = pUsername)
THEN
SET pErrorCode = -1;
ELSE
SET pErrorCode = 1;
END IF;
SELECT pErrorCode AS res;
END$$
DELIMITER ;
Schema:
-- drop table if exists mt_user;
create table mt_User
( UserID int auto_increment primary key,
UserName varchar(100) not null,
unique key(UserName)
);
insert mt_User(UserName) values ('dev');
select * from mt_User;
Test:
set #var1:=-4;
call usp_GetUserValidation('dev',#var1);
-- returns (-1) ---- Yea, we like that
select #var1;
-- (-1)
set #var1:=-4;
call usp_GetUserValidation('dev222',#var1);
-- returns 1 ---- Yea, we like that
select #var1;
-- 1

How to get total count of two tables using stored procedure?

I need to create a stored procedure for getting the count of two table by using where clause condition, but when i try to create procedure it shows error
Query : CREATE PROCEDURE bcp.getTotalCount BEGIN -- Create two integer values DECLARE #tableOneCount int, #tableTwoCount int -- Get ...
Error Code : 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 'BEGIN
-- Create two integer values
DECLARE #tableOneCount int, #tableTwoCount' at line 2
This is the stored procedure i tried to create
DELIMITER $$
DROP PROCEDURE IF EXISTS bcp.getTotalCount $$
CREATE PROCEDURE bcp.getTotalCount
BEGIN
-- Create two integer values
DECLARE #tableOneCount INT, #tableTwoCount INT
-- Get the number of rows from the first table
SELECT #tableOneCount = (SELECT COUNT(*) FROM candidates WHERE active=1)
SELECT #tableTwoCount = (SELECT COUNT(*) FROM voters_enrollment WHERE active=1)
-- Return the sum of the two table sizes
SELECT TotalCount = #tableOneCount + #tableTwoCount
END $$
DELIMITER ;
For better understanding i tried with simple sql query like this
SELECT (SELECT COUNT(*) FROM candidates WHERE active=1)+
(SELECT COUNT(*) FROM voters_enrollment WHERE active=1) AS Total
I get the result as
Total
10
Like this way i need to create the procedure and call it to get the same result by using simple sql query. can anyone help me to solve this please.
You have to put AS after the create statement.
DELIMITER $$
DROP PROCEDURE IF EXISTS bcp.getTotalCount $$
CREATE PROCEDURE bcp.getTotalCount
AS
BEGIN
-- Create two integer values
DECLARE #tableOneCount INT, #tableTwoCount INT
-- Get the number of rows from the first table
SELECT #tableOneCount = (SELECT COUNT(*) FROM candidates WHERE active=1)
SELECT #tableTwoCount = (SELECT COUNT(*) FROM voters_enrollment WHERE active=1)
-- Return the sum of the two table sizes
SELECT TotalCount = #tableOneCount + #tableTwoCount
END $$
DELIMITER ;
You can try this, mate:
DELIMITER $$
DROP PROCEDURE IF EXISTS bcp_getTotalCount $$
CREATE PROCEDURE bcp_getTotalCount()
BEGIN
-- clear/initialize session variables
SET
#tableOneCount = 0,
#tableTwoCount = 0;
START TRANSACTION;
-- get record count from the source tables
SELECT COUNT(*) INTO #tableOneCount FROM candidates WHERE active = 1;
SELECT COUNT(*) INTO #tableOneCount FROM voters_enrollment WHERE active = 1;
-- return the sum of the two table sizes
SELECT TotalCount = #tableOneCount + #tableTwoCount;
COMMIT;
END $$
DELIMITER ;
MySQL Transaction for Atomicity

phpMyAdmin - SELECT statement's result in stored procedure not showing

I Have created a simple procedure:
CREATE PROCEDURE `simpleProcedure` ( IN `parameter` INT) NOT DETERMINISTIC READS SQL DATA SQL SECURITY DEFINER
BEGIN
SELECT *
FROM table1;
END
Running this procedure using CALL simpleProcedure(1) in phpMyAdmin does not show the result of the query... How do I make phpMyAdmin show the result of the query inside the procedure?
You need an OUT parameter for it to return results, see http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html.
Example from the sakila database:
DELIMITER $$
CREATE DEFINER=`root`#`127.0.0.1` PROCEDURE `film_in_stock`(IN p_film_id INT, IN p_store_id INT, OUT p_film_count INT)
READS SQL DATA
BEGIN
SELECT inventory_id
FROM inventory
WHERE film_id = p_film_id
AND store_id = p_store_id
AND inventory_in_stock(inventory_id);
SELECT FOUND_ROWS() INTO p_film_count;
END$$

MySql Stored procedure shows as error in syntax

I am new to creating procedures in mysql, i know how to create them in MSSQL, but i am not sure what is wrong with this, it says Syntax Error Near END
CREATE PROCEDURE GetNameByID(IN CustID INT)
BEGIN
SELECT * FROM Customers WHERE CustomerID = CustID
END
The query in your procedure needs a semi colon after it:
CREATE PROCEDURE GetNameByID(IN CustID INT)
BEGIN
SELECT * FROM Customers WHERE CustomerID = CustID;
END
You may also need to set the delimiter to something. The MySQL documentation does this:
DELIMITER //
CREATE PROCEDURE GetNameByID(IN CustID INT)
BEGIN
SELECT * FROM Customers WHERE CustomerID = CustID;
END//
(but obviously not with your query)
You are missing the ; at the end of select statement