How to create a table with consecutive numbers - mysql

I need a helper table with only one int(11) column, that contains a row for each consecutive number from 1 to a given max. Can this be done with pure SQL?
Example:
INSERT INTO `helper`('itnum') VALUES (1),(2),(3),...(999999),(1000000);
I need a statement like this, but without explicitly listing all the entries to be made.

How about something like this:
DELIMITER |
DROP PROCEDURE IF EXISTS insert_helper_records |
CREATE PROCEDURE insert_helper_records(a_max INTEGER)
BEGIN
DECLARE v_iteration INTEGER;
SET v_iteration := 1;
insert_loop: LOOP
INSERT INTO helper(itnum) VALUES (v_iteration);
SET v_iteration := v_iteration + 1;
IF v_iteration = a_max THEN
LEAVE insert_loop;
END IF;
END LOOP;
END |
DELIMITER ;
Then call it however you want like:
SELECT insert_helper_records(999999) FROM DUAL;

i think to do this, you have to execute your insert inside a loop in your SGBD procedure, or outside (php script, ...).

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);

How to set MySQL parameter multiple values in variable

I'm trying to assign multiple values in a variable and execute a query using it. For example below:
SET #ledger = "'Cash','Special Offer'";
SELECT `_ledger` FROM `acc_ledger` WHERE `_ledger` IN(#ledger);
But this doesn't work as planned. Is there a way to define multiple values in a variable? If yes, how? If no, can I have a suggestion on how to tackle this issue?
You can pass multiple values with comma separated and then split those variables int table and perform a join
create function to split comma separated parameter
DELIMITER $$
DROP FUNCTION IF EXISTS `SPLIT_STR` $$
CREATE FUNCTION SPLIT_STR(id_list VARCHAR(500), delimeter VARCHAR(10), position INT)
RETURNS VARCHAR(10)
DETERMINISTIC
BEGIN
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(id_list, delimeter, position),
LENGTH(SUBSTRING_INDEX(id_list, delimeter, position - 1)) + 1),
delimeter, '');
END$$
DELIMITER ;
call SPLIT_STR function from query
SET #ledger = "Cash,Special Offer";
CREATE TEMPORARY TABLE IF NOT EXISTS `selected_types` (type varchar(50));
#inserting splitted values to temp table
simple_loop: LOOP
SET indx=indx+1;
SET str=SPLIT_STR(x_id_list,',',indx);
IF str='' THEN
LEAVE simple_loop;
END IF;
INSERT INTO selected_types VALUES(str);
END LOOP simple_loop;
#filter with temp table
SELECT `_ledger` FROM
`acc_ledger` led
inner join selected_types tmp on tmp.type = led._ledger;

MySQL puzzle: How to combine result in Loop?

So far I have tried using CREATE VIEW <view_table_name> and
CREATE TABLE <table_name> and CREATE TEMPORARY <temporary_table_name>
and this methods are taking so much time because I have to (step 1) create a table and (step 2) insert a data. Then (step 3) select the created table. Finally, (step 4) drop the table.
This is my procedure: (My program doesn't look make any sense, I mean why am I doing this. The answer to your confusion is, this is just a part of my large code and I made it this way so that it may look simple.)
BEGIN
-- Main loop variables
DECLARE col_Name varchar(255);
DECLARE col_Description varchar(255);
-- Main Loop
Block2: BEGIN
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE statement CURSOR FOR SELECT `name`, `description` FROM `rules`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN statement;
REPEAT
MainLoop: LOOP
FETCH statement INTO col_Name, col_Description;
IF done THEN
LEAVE MainLoop;
END IF;
SELECT col_Name AS `Name`, col_Description AS `Description`;
END LOOP MainLoop;
UNTIL done END REPEAT;
CLOSE statement;
END Block2;
-- End of Main Loop
END
The result is:
The problem:
The result is separate. How do I combine this result into one table?
Declare a temporary table at the beginning ,populate data into temp table and then access it after loop ends
BEGIN
-- Main loop variables
DECLARE col_Name varchar(255);
DECLARE col_Description varchar(255);
create temporary table yourtable (name varchar(50),description varchar(50));
-- Main Loop
Block2: BEGIN
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE statement CURSOR FOR SELECT `name`, `description` FROM `rules`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN statement;
REPEAT
MainLoop: LOOP
FETCH statement INTO col_Name, col_Description;
IF done THEN
LEAVE MainLoop;
END IF;
insert into yourtable(name,description)
values (col_Name, col_Description)
END LOOP MainLoop;
UNTIL done END REPEAT;
CLOSE statement;
select * from yourtable
END Block2;
-- End of Main Loop
END
I think things can be easier.
you don't have to use a cursor, you just need to create an empty table in your procedure, and input the result from your query.
like below:
CREATE DEFINER=`root`#`localhost` PROCEDURE `temp`(val int)
BEGIN
DECLARE yourval datatype()
-- declare as many as you need.---
set #beginning = 0
set #ending = val
-- how many time do you need to repeat your code?
---CREATE AN EMPTY TABLE HERE---
while #beginning < #ending do
insert table TableCreatedAbove
---YOUR QUERY---
---YOU MAY NEED TO DO SOMETHING WITH YOUR DECLARED VARIABLE---
set #beginning = #beginning + 1;
end while;
commit;
END
when you need to use your combined table, just
select * from TableCreatedAbove
maybe you already solved your problem in somewhere else, but here is my answer.

MySQL: How do a i insert a specific number of blank rows into a table

I want to grab a variable (between 1-365) and use this value to create the number of empty rows in a table:
insert into tblCustomer (ID) values (), (), ();
is there an easier way to do this or is using a loop the best way?
Any help would be appreciated.
A procedure with an IN parameter is quite easy
DELIMITER $$
DROP PROCEDURE IF EXISTS test_loop$$
CREATE PROCEDURE test_loop(IN number INT)
BEGIN
DECLARE x INT(11);
SET x = 1;
WHILE x <= number DO
INSERT INTO tblCustomer(id) VALUES('');
SET x = x + 1;
END WHILE;
END$$
DELIMITER ;
How to use it
CALL test_loop(20);

while loop terminating after fetching some data

I have written a procedure that creates a temporary table and executes a query by fetching the rows from the temporary table.I have around 13486 rows in the temporary table.But when i am calling the procedure i observed that the procedure is getting terminated after fetching 107 rows from the temporary table.Moreover i also observed that this value is not constant..Sometimes it is 107 the other time it is 114 and some other time it is just 100.Why this happens?Please need help?Somebody please..Here is my procedure.And i came to know that while loop will terminate for >1000 iterations.Please suggest me a method to overcome this.
DELIMITER $$
DROP PROCEDURE IF EXISTS `lookup`.`test` $$
CREATE PROCEDURE `lookup`.`test` ()
BEGIN
CREATE TEMPORARY TABLE lookup.airportname(id int AUTO_INCREMENT,PRIMARY KEY(id))
AS (select distinct airport_id from lookup.airport);
SET #num=0;
SET #arpt=NULL;
SELECT count(*) INTO #num FROM airportname;
SET #i=0;
while #i<#num do
SELECT airport_id INTO #arpt FROM airportname WHERE id=#i;
select #arpt,#i;
set #i=#i+1;
end while;
END $$
DELIMITER ;
I am using mysql query browser.Thank you.
If you want to insert value into id Then it should not be auto_increment. - Remove auto_increment from table definition, it should work
delimiter |
create procedure employee_select()
Begin
Declare empno,done int(9);
Declare emp_select Cursor for select emp_no from gross_salary ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
Open emp_select; // cursor opening
read_loop: loop // start looping all the datas one by one
fetch emp_select into empno; // fetching the select value into variable empno
//note :variable name should not be same as columne name in select statement"
IF done THEN
LEAVE read_loop; // if no more rows, this makes it to leave the loop"
END IF;
//Enter the code you want do for each row
end loop;
close emp_select;
End |
delimiter ;