How do i get column values of my sql table dynamically using stored procedures? - mysql

I am learning stored procedures. Coming to the problem I have a table where columns are named as Q1,Q2,Q3...,Q10 . I want to retrieve these values dynamically using while loop (or for loop). I tried something but that didn't give me actual output. Please give me some suggestions.
My code is as follows :
delimiter //
drop procedure if exists exam//
create procedure exam ()
begin
declare a int default 1;
while a <= 9 do
select concat(Q,a) from feed1 where col = 'XYZ';
set a= a + 1;
end while;
end ;
//
delimiter ;
call exam;
When i run this i am getting an error " Unknown column Q in field list "

Related

Why won't MYSQL procedure properly iterate new ROWS in TABLE using WHILE statement?

I am creating this basic procedure using MySQL Workbench to accept a single input parameter.
The table "unique_days" has a single PRIMARY KEY column called "dayid" which currently has a single ROW with a value of 1.
DROP PROCEDURE IF EXISTS dayid_iteration;
DELIMITER $$
CREATE PROCEDURE dayid_iteration(maxdate_final INT)
BEGIN
DECLARE maxdate_current INT;
SET #maxdate_current = (SELECT (MAX(dayid) + 1) FROM unique_days);
DELETE FROM unique_days WHERE dayid > 1;
WHILE (maxdate_current > maxdate_final) DO
INSERT INTO unique_days (dayid) VALUES (maxdate_current);
SET maxdate_current = (maxdate_current+1);
END WHILE;
END$$
DELIMITER ;
The procedure is then called with an integer parameter.
CALL dayid_iteration(11);
The variables are setting properly because I can run a select statement with the variable and it shows the correct new value. The deletion of dayid > 1 also works (Tested by manually adding additional rows, and then running procedure). However, I can't seem to get the WHILE statement to insert new rows with the value provided.
Any help is much appreciated. I searched multiple other questions, and countless forums, but everything looks like it should be working.
I am expecting the code to CREATE 9 ROWS for a total of 10 ROWS.
The following is included just so you can see the starting values of the table.
SELECT * FROM unique_days;
For anyone who finds this question, the following code functions correctly. The input variable on the parameter was not setting properly. Once the parameter had "IN" placed in front of the variable name, it correctly received the parameter.
CREATE PROCEDURE dayid_iteration(IN maxdate_final INT)
DROP PROCEDURE IF EXISTS dayid_iteration;
DELIMITER $$
CREATE PROCEDURE dayid_iteration(IN maxdate_final INT)
BEGIN
DECLARE maxdate_current INT;
SET maxdate_current = (SELECT (MAX(dayid) + 1) FROM unique_days);
WHILE (maxdate_current <= maxdate_final) DO
INSERT INTO unique_days (dayid) VALUES (maxdate_current);
SET maxdate_current = (maxdate_current+1);
END WHILE;
END$$
DELIMITER ;
CALL dayid_iteration(1000);
This call procedure now properly works.
CALL dayid_iteration(1000);

MySQL updating data in a column using a loop

I created a little program to show my students how to use loops in MySQL (Workbench).
The program updates a column in a table with test data. I want to add a range of interest rates. When I run the program, the same interested rate is entered into each row.
CREATE TABLE mtgPayment
(lengthMonths DECIMAL(4,0),
mInterest DECIMAL(8,6),
loanAmt DECIMAL(10,2));
DELIMITER $$
CREATE PROCEDURE test_data()
BEGIN
DECLARE i DECIMAL(8,6) DEFAULT 2.0;
WHILE i < 3.5 DO
UPDATE mtgpayment set mINTEREST = i;
SET i = i + .5;
END WHILE;
END$$
DELIMITER ;
CALL test_data();
SELECT * FROM mtgpayment;

SQL stored procedure- where am I going wrong?

I'm trying to create a stored procedure that calculates total revenue from a customer by if it's occupied and the standard rate. I am getting an error message and when I try to call from it I get NULL. Can anyone help? Thanks.
//Delimiter
CREATE PROCEDURE calculateRevenue (in customerIDs int, OUT totalRevenue dec(15,2))
BEGIN
SELECT SUM(Occupied*StandardRate) into totalRevenue FROM climatesouth
WHERE customerIDs = customerID;
END //
delimiter//
call calculateTotal(10, #totalRevenue);
SELECT #totalRevenue;
First you need to give your input parameters different names from the columns. Then you need to use them. Also, DELIMITER goes before the stored procedure definition:
DELIMITER //
CREATE PROCEDURE calculateRevenue (
in in_customerIDs int,
out out_totalRevenue dec(15,2))
BEGIN
SELECT SUM(cs.Occupied cs.* cs.StandardRate) into out_totalRevenue
FROM climatesouth cs
WHERE cs.customerID = in_customerID;
END //
The delimiter assignment is off: your are setting it to // after the create procedure statement.
Also, the parameter name needs to be fixed: your are not using the correct name in the query (your parameter has a trailing 's'), because of which the procedure will not produce the result you expect.
So:
delimiter // -- change the default delimiter here
create procedure calculaterevenue (in p_customerid int, out p_totalrevenue dec(15,2))
begin
select sum(occupied * standardrate) into p_totalrevenue
from climatesouth
where customerid = p_customerid; -- "p_customerid" is the parameter name
end //
delimiter ; -- reset the delimiter, now we can call the procedure
call calculaterevenue(10, #totalrevenue);
select #totalrevenue;
It is easier just to return the result as a result set rather than to use the OUT-parameter. The OUT-parameters are usually used only when calling procedure from another procedure. If you call the procedure from your application, use the result set.
delimiter //
CREATE PROCEDURE calculateRevenue (in_customerID int)
BEGIN
SELECT SUM(Occupied*StandardRate) as totalrevenue
FROM climatesouth
WHERE customerID = in_customerID;
END
//
delimiter ;
call calculateRevenue(10);

Trouble with calling a stored procedure within an stored procedure and setting result as a variable

I'm trying to call a stored procedure from another stored procedure and store the value in a variable. The inner stored procedure basically checks if something exists and uses a select statement to return a zero or one. I keep getting an error. In this situation, MySQL is saying "=" is not valid at this position, expecting ";"
CREATE PROCEDURE `CardNames_Add` (searchedCard VARCHAR(50))
BEGIN
DECLARE exist TINYINT;
EXECUTE exist = CardNames_CheckExist searchedCard
IF (exist = 0)
INSERT INTO card_names (name)
VALUE(searchedCard)
END
You have to rewrite you other stored procedure, that you don't need btw, to give back a result
CREATE PROCEDURE CardNames_CheckExist (IN searchedCard VARCHAR(50), OUT result TINYINT )
BEGIN
--do some stuzff
result = 1
END
CREATE PROCEDURE `CardNames_Add` (searchedCard VARCHAR(50))
BEGIN
CALL CardNames_CheckExist(searchedCard,#result);
IF (#result = 0) THEN
INSERT INTO card_names (name)
VALUES (searchedCard);
END IF;
END

MYSQL declaring variables

I don't get what is wrong with this script
BEGIN
DECLARE crs INT DEFAULT 0;
WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs)
SET crs = crs + 1;
END WHILE;
END;
I want it to insert 10 values into the table continent but there is an error at the second line.
declare variable in MySQL with # and assign with :=
SET #crs = 0; // declaration
--here your query
#crs := #crs+1 // assignment
References
user defined variables
assignment
MySQL does not support the execution of anonymous blocks of stored procedure code.
You need to create a stored procedure including that code and then invoke it.
Also, you were missing the semi-colon at the end of your insert statements. I fixed that. You also probably want to use concat() instead of + to generate the names, but I'll leave that change to you.
Create the procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS insert_ten_rows $$
CREATE PROCEDURE insert_ten_rows ()
BEGIN
DECLARE crs INT DEFAULT 0;
WHILE crs < 10 DO
INSERT INTO `continent`(`name`) VALUES ('cont'+crs);
SET crs = crs + 1;
END WHILE;
END $$
DELIMITER ;
Invoke the procedure:
CALL insert_ten_rows();