Insert results of a stored procedure into an existing table - mysql

I have a table called Percentages with a Column called 5StarResults, I would like to populate this with the results of a stored procedure names 5star.
When I use 'Call 5star' it returns just a percentage, I would like this percentage inserted into the Percentages table.
Please can you assist, I have tried to edit the procedure to include an Insert but it always returns saying 0 rows inserted.
Thank you
edit,
Stored Procedure is as follows
BEGIN
declare Rating5Total int default 5;
declare Rating5Win int default 5;
declare 5StarPerformance decimal;
set Rating5Total = (select COUNT(Ratings) from vHighPerformance where Ratings = 7);
set Rating5Win = (select COUNT(Results) from vHighPerformance where Ratings = 7 and Results = 1);
set 5StarPerformance = Rating5Win*100.0/Rating5Total;
Select 5StarPerformance;
END

If an option is to do the INSERT in the same stored procedure, the following code should work:
CREATE PROCEDURE `5star`()
BEGIN
DECLARE Rating5Total INT DEFAULT 5;
DECLARE Rating5Win INT DEFAULT 5;
DECLARE 5StarPerformance DECIMAL(18, 3);
SET Rating5Total := (SELECT COUNT(Ratings) FROM vHighPerformance WHERE Ratings = 7);
SET Rating5Win := (SELECT COUNT(Results) FROM vHighPerformance WHERE Ratings = 7 AND Results = 1);
SET 5StarPerformance := Rating5Win*100.0/Rating5Total;
/* INSERT INTO percentages (percentage) VALUES (5StarPerformance); */
INSERT INTO percentages (id, percentage) VALUES (1, 5StarPerformance)
ON DUPLICATE KEY UPDATE percentage = 5StarPerformance;
SELECT 5StarPerformance;
END$$
An example can be seen in SQL Fiddle.
UPDATE
If you need one single record on table percentages, you can make a UPSERT. See the updated code.

Related

how to insert multiple rows in table using store procedure parameter in mysql

i have three table product,sizes and product_size
product
> id
> name
product_size
> product_id FK
> size_id FK
size
> id
> name
Know using store procedure i want to insert single product with muliple sizes
eg.
product.id =1;
product.name = xyz;
{
product_size.product_id = 1
product_size.size_id = 1
product_size.product_id = 1
product_size.size_id = 2
product_size.product_id = 1
product_size.size_id = 3
}
So how to pass sizes parameter to store procedure in mysql
The following is a stored procedure that inserts one record into product_size each time you call the procedure. The procedure takes input parameters for product.id and size.id.
DELIMITER //
CREATE PROCEDURE INSERT_product_size(
IN productID int,
IN sizeID int
)
BEGIN
INSERT INTO
product_size
(product_id, size_id)
VALUES
(productID, sizeID);
END //
DELIMITER ;
This procedure takes a single product id and an "array" of size id's (in the form of a comma-delimited string) and inserts all sizes for the product in one procedure call:
DROP PROCEDURE IF EXISTS INSERT_product_sizes;
DELIMITER //
CREATE PROCEDURE IF NOT EXISTS INSERT_product_sizes(
IN productID int,
IN sizeIDs varchar(100)
)
BEGIN
DECLARE delimiterCount int;
DECLARE sizeID int;
DECLARE loopCount int;
/* Remove spaces, if any, from input string */
SET sizeIDs = REPLACE(sizeIDs, ' ', '');
/* Determine how many commas are in input string */
SET delimiterCount = LENGTH(sizeIDs) - LENGTH(REPLACE(sizeIDs, ',', ''));
SET loopCount = 1;
/* For each id in input string */
WHILE loopCount <= delimiterCount + 1 DO
SET sizeID = SUBSTRING_INDEX(sizeIDs, ',', 1);
INSERT INTO
product_size
(product_id, size_id)
VALUES
(productID, sizeID);
/* Remove last used id from input string */
SET sizeIDs = REPLACE(sizeIDs, CONCAT(sizeID, ','), '');
SET loopCount = loopCount + 1;
END WHILE;
END //
DELIMITER ;
If you want all sizes attached to a product on an insert then a simple
insert into product_size(product_id,size_id)
select inprodid,name
from size
;
will do.
But if you only want some sizes then you could pass the sizes as a delimited string , split them in the procedure in a loop which would include an insert statement. You will find examples of how split strings if you google mysql split string.

How to write a query on mysql which will calculate how many days in a row by this time the user visited the application

I have table like:
CREATE TABLE Activity (LoginDate DATE, ID int);
INSERT INTO Activity VALUES
("2016-10-01", 2), ("2016-10-01", 1), ("2016-10-02", 1), ("2016-10-02", 3),
("2016-10-03", 1), ("2016-10-03", 3), ("2016-10-04", 2), ("2016-10-05", 1);
and need to recieve something like this:
table
<table><tbody><tr><th>Date</th><th>UserID</th><th>Days in Row</th></tr><tr><td>2016-10-01</td><td>2</td><td>0</td></tr><tr><td>2016-10-01</td><td>1</td><td>0</td></tr><tr><td>2016-10-02</td><td>1</td><td>1</td></tr><tr><td>2016-10-02</td><td>3</td><td>0</td></tr><tr><td>2016-10-03</td><td>1</td><td>2</td></tr><tr><td>2016-10-03</td><td>3</td><td>1</td></tr><tr><td>2016-10-04</td><td>2</td><td>0</td></tr><tr><td>2016-10-05</td><td>1</td><td>0</td></tr></tbody></table>
by using only sql or t-sql, without CTE. Any ideas?
I don't have MySQL, so take this more as just pseudo code. Could something like this work for you?
CREATE PROCEDURE TrackConsecutiveVisits()
BEGIN
CREATE TABLE Activity_Results (LoginDate DATE, ID int, con_visits int);
DECLARE con_visit INTEGER DEFAULT 0;
DECLARE last_id INTEGER DEFAULT 0;
DECLARE last_date DATE DEFAULT "1900-01-01";
DECLARE cur_id INTEGER DEFAULT 0;
DECLARE cur_date DATE DEFAULT "1900-01-01";
DECLARE concur CURSOR FOR
SELECT ID,
LoginDate
FROM Activity
ORDER
BY id,
loginDate;
OPEN con_cursor;
con_loop: LOOP
FETCH concur INTO cur_id, cur_date;
IF last_id = cur_id AND last_date + 1 = cur_date THEN
SET con_visit = con_visit + 1
ELSE
SET con_visit = 0
END IF
INSERT INTO Activity_Results VALUES (cur_id, cur_date, con_visit)
SET last_id = cur_id;
SET last_date = cur_date;
END LOOP
CLOSE concur
END;

Use MySQL query result in a loop

I just started working with SQL and have been working with MySQL.I am trying to write a stored procedure that will take each value from my buyPrice column in my products table, and store each value into a variable. I then want it to multiply this variable by the sales tax and then take each result and place it into my empty sales_tax column. I would like to populate the whole column with the sales tax for each item. When I execute this method I get some error saying the productCode doesn't have a default value. What is the proper way to write this? I know this isn't the most efficient way of doing this task, just trying to practice.
DELIMITER //
CREATE PROCEDURE nFirstProcedure()
BEGIN
DECLARE IdValue, counter, holdValue, result INT DEFAULT 0;
DECLARE holdName VARCHAR(30);
SET counter = 1;
WHILE counter < ( SELECT COUNT(*) FROM products)
DO
SET holdValue = (SELECT buyPrice FROM products WHERE sales_tax = null);
SET result = (holdValue * 0.08);
INSERT INTO products (sales_tax) VALUES (result);
END WHILE;
END//
DELIMITER ;
You should not do this with a loop. Just use update:
update products
set sales_tax = buyPrice * 0.08
where sales_tax is null;

Creating MySQL Temporary Table then Assign CRUD From It

i have created a stored procedure which have logic like this:
getting the data result from 2 tables then create temporary table based on it (the data range is selected using two parameter start date and end date).
select few columns from the temporary table then assign to another table (eg. X)
update the table (X).
this is my stored procedure syntax:
DELIMITER $$
USE `sre`$$
DROP PROCEDURE IF EXISTS `sp_checkPotentialProductf`$$
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_checkPotentialProductf`(IN sdate DATE, IN edate DATE)
BEGIN
DECLARE sumtotal INT DEFAULT 0;
DECLARE first_margin DOUBLE;
DECLARE count_rows INT DEFAULT 0;
DECLARE startnum INT DEFAULT 0;
DECLARE start_mrg DOUBLE;
DECLARE adder DOUBLE;
/* assign table temporary and select the values */
CREATE TEMPORARY TABLE IF NOT EXISTS vShowTopSellingQuantitys AS
SELECT
`mt_pesanan`.`ms_langganan_idms_langganan` AS `idms_langganan`,
`mt_pesanan`.`ms_langganan_idms_kodebarang` AS `idms_kodebarang`,
`md`.`nama` AS `nama`,
`mt_pesanan`.`quantity` AS `quantity`,
`mt_pesanan`.`harga` AS `harga`,
`mt_pesanan`.`jumlah` AS `jumlah`,
`mt_pesanan`.`discount` AS `discount`,
`mt_pesanan`.`tgl_pesan` AS `tgl_pesan`,
SUM(`mt_pesanan`.`quantity` ) AS `sum_product`
FROM `mt_pesanan` JOIN `ms_barang` `md`
WHERE ((`mt_pesanan`.`tgl_pesan` <= edate) AND (`mt_pesanan`.`tgl_pesan` >= sdate))
AND (md.`idms_kodebarang` = `mt_pesanan`.`ms_langganan_idms_kodebarang`)
GROUP BY `mt_pesanan`.`ms_langganan_idms_kodebarang`
ORDER BY SUM(`mt_pesanan`.`quantity` ) DESC;
/* end assign table temporary */
/* assign values to variables */
SELECT SUM(sum_product) INTO sumtotal FROM `vShowTopSellingQuantitys`;
SELECT COUNT(sum_product) INTO count_rows FROM `vShowTopSellingQuantitys`;
SELECT (sum_product/sumtotal)*100 INTO first_margin FROM `vShowTopSellingQuantitys` LIMIT 1;
/* truncate database tmp*/
TRUNCATE tmp_produkpotensial;
/*creating algorithm to analyze the percentage quantity/total */
SET startnum = 1;
/*show result with percentage*/
SELECT `idms_kodebarang`, `nama`, sum_product , ((sum_product/sumtotal)*100) AS 'pecentage_margin' FROM `vShowTopSellingQuantitys`;
/*result execution from temporary table to analyze potential product */
INSERT INTO tmp_produkpotensial(idms_kodebarang,nama,percentage_margin)
SELECT `idms_kodebarang`, `nama`, ((sum_product/sumtotal)*100) AS 'percentage_margin' FROM `vShowTopSellingQuantitys`;
/* update the sum total of percentage */
WHILE(count_rows >= startnum) DO
IF(startnum = 1) THEN
SET start_mrg = 0;
UPDATE tmp_produkpotensial SET tmp_produkpotensial.sum_margin = (percentage_margin + start_mrg) WHERE id_barang = startnum;
ELSE
SELECT sum_margin INTO start_mrg FROM tmp_produkpotensial WHERE id_barang = (startnum - 1);
UPDATE tmp_produkpotensial SET tmp_produkpotensial.sum_margin = (percentage_margin + start_mrg) WHERE id_barang = startnum;
END IF;
/* Assign Update to Update Sum Margin Column */
SET startnum = startnum + 1;
END WHILE;
END$$
DELIMITER ;
The stored procedure is successfully compiled, but when i call the stored procedure it always returns 0 rows.
syntax to call the stored procedure:
CALL `sp_checkPotentialProductf`('2012-12-31','2012-01-01');
My Questions:
can temporary table is used again to create further CRUD statement?
is there any ideas where the fails goes on?
thanks
okay, i have discovered a mistake. The method to call the stored procedure is
CALL `sp_checkPotentialProductf`(2012-12-31,2012-01-01);
without the quotes.

Stored Procedure taking ages to execute?

DELIMITER $$
CREATE PROCEDURE Load_Fact_List()
BEGIN
DECLARE Project_Number_Temp INT;
DECLARE Panel_Id_Temp INT;
DECLARE Employee_Id_Temp INT;
DECLARE Zip_Temp VARCHAR(255);
DECLARE Created_Date_Temp DATE;
DECLARE Country_Temp VARCHAR(255);
DECLARE no_more_rows BOOLEAN;
DECLARE loop_cntr INT DEFAULT 0;
DECLARE num_rows INT DEFAULT 0;
DECLARE load_cur CURSOR FOR
SELECT Project_Id, Panel_Id, Employee_Id, Zip, Created_Date
FROM Fact_List;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET no_more_rows = TRUE;
OPEN load_cur;
select FOUND_ROWS() into num_rows;
the_loop: LOOP
FETCH load_cur
INTO Project_Number_Temp, Panel_Id_Temp, Employee_Id_Temp, Zip_Temp, Created_Date_Temp;
IF no_more_rows THEN
CLOSE load_cur;
LEAVE the_loop;
END IF;
SET Country_Temp= (select Country from Zip where Zip= Zip_Temp);
INSERT INTO Test_Fact
(
Project_Key,
Campaign_Key,
Respondents_Key,
Event_Key,
Employee_Key,
Geography_Key,
Date_Key
)
SELECT (SELECT Project_Key from Project_Dim where Project_Id= Project_Number_Temp AND Quota_Country= Country_Temp),0,(SELECT MAX(Respondents_Key) from Respondents_Dim WHERE Panel_Id= Panel_Id_Temp),1,(select MAX(Employee_Key) from Employee_Dim WHERE Employee_Id= Employee_Id_Temp),(Select Geography_Key from Geography_Dim where Zip= Zip_Temp), (Select Date_Key from Date_Dim where Full_Date= Created_Date_Temp);
SET loop_cntr = loop_cntr + 1;
END LOOP the_loop;
select num_rows, loop_cntr;
END $$
The above code is properly working but it is damn slow. For every 1 hour it is loading 1000 records. I got lacks of records to load into fact table. can anyone suggest me any optimization?
Requirement is to load fact table by looping through other table and gathering required key values from dimension tables.
The usual procedure is actually like this.
You have your dimensions built and you just gathered the data you want to insert into your fact table in a temporary table. Then you insert this data in another temporary table like this:
INSERT INTO tmp_fact_table
(
fact_key,
dim1_key,
dim2_key,
...
fact1,
fact2
...
)
SELECT
ISNULL (f.fact_key, 0),
ISNULL (d1.sid, 0) as whatever,
ISNULL (d2.sid, 0) as whatever2,
...
ISNULL (tt.fact1, 0),
ISNULL (tt.fact2, 0)
FROM
yourTempTable tt
LEFT JOIN Dim1 d1 ON tt.identifying_column = d1.identifying_column
...
LEFT JOIN fact_table f ON
f.dim1_key = d1.sid
AND f.dim2_key = d2.sid
where
fact_key is the identifying column in your fact table
dim1_key is the foreign key in your fact table to the dimensions
fact1 and so on are the facts you want in your fact table, clear
the ISNULL() function returns 0 when no entry is found. 0 is the id of your dummy row in each dimension for unknown data
Then you will have a table where you have the IDs of your dimensions linked to the data you want to import into your fact table with 0 as fact key when the entry in the fact table does not already exist and the ID of the fact table entry otherwise.
Then you update the fact table where tmp_fact_table.fact_key != 0
Then you insert into the fact table where tmp_fact_table.fact_key = 0
That's it.
I'm doing this with millions of rows and it takes about half an hour. 300,000 rows is peanuts.