Store Procedure Concat a select while in a loop - mysql

I'm building a serie of Procedures where I'll have to insert generic names in almost all of them, and multiples columns.
So I thought in create a Procedure to Generate a "text" for me. The code for the text is this:
SELECT CONCAT( CHAR( FLOOR(65 + (RAND() * 25))));
This generates one random char for me. So this is the procedure that I made:
DELIMITER ;;
CREATE DEFINER=`my_definer`#`localhost` PROCEDURE GenericName(IN NumRows INT,OUT retorno VARCHAR)
BEGIN
DECLARE i INT;
SET i = 1;
SET retorno = "";
WHILE i <= NumRows DO
SET retorno = SELECT CONCAT( CHAR( FLOOR(65 + (RAND() * 25))));
SET i = i + 1;
END WHILE;
END;;
DELIMITER ;
The following error is what is appearing when I try to create the procedure:
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 DECLARE i INT; SET i = 1; SET retorno = "";
Based on the error, I think is something stupid, but I don't have much of expertise in creating Store Procedures and I may be overthinking something.
PS (this is the future usage that I'm planing to do when I finish the procedure above): The idea is to call this procedure in other procedures by something like:
INSERT INTO tbl_a (name, position) VALUES (CALL GenericName(7), CALL GenericName(5));
External links:
I saw that is possible to call a procedure from another procedure here "Calling a Stored Procedure in a Stored Procedure in MySQL"

PROBLEM #1
You should not be using a Stored Procedure. You should be using a Stored Function
PROBLEM #2
In the loop, you forgot to include retorno in the CONCAT
PROBLEM #3
Also, I would change
CHAR(FLOOR(65 + (RAND() * 25)))
to
CHAR(FLOOR(65.5 + (RAND() * 25)))
to give the letter Z a fair chance to appear
PROBLEM #4
Replace
SET retorno = SELECT CONCAT(...
with
SET retorno = CONCAT(...
PROPOSED STORED FUNCTION
DELIMITER ;;
CREATE DEFINER=`my_definer`#`localhost` FUNCTION GenericName
(NumRows INT)
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
DECLARE i INT;
DECLARE retorno VARCHAR(20);
SET i = 1;
SET retorno = "";
WHILE i <= NumRows DO
SET retorno = CONCAT(retorno,CHAR(FLOOR(65.5 + (RAND() * 25))));
SET i = i + 1;
END WHILE;
RETURN retorno;
END;;
DELIMITER ;
Then, you can call the INSERT like this
INSERT INTO tbl_a (name, position) VALUES (GenericName(7),GenericName(5));
GIVE IT A TRY !!!

Related

Using a custom(user-defined) function inside a procedure in mysql

In the code below, there's a function that generates a random string, and a procedure that is supposed to insert random strings into a table called Users. I have successfully created the function and it's working without any problem, but when I try to create the procedure, it returns a syntax error at line "SET #str = SELECT randstring(8);" I think I am trying to call my function in a wrong way. I'm new to databases so please bear with me.
DELIMITER $$
CREATE FUNCTION `Randstring`(LENGTH SMALLINT(3)) RETURNS VARCHAR(100) CHARSET utf8
BEGIN
SET #returnStr='';
SET #allowedChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
SET #i = 0;
WHILE (#i < LENGTH) DO
SET #returnStr = CONCAT(#returnStr, SUBSTRING(#allowedChars, FLOOR(RAND() * LENGTH(#allowedChars) + 1), 1));
SET #i = #i + 1;
END WHILE;
RETURN #returnStr;
END
DELIMITER $$
CREATE PROCEDURE insertdata()
BEGIN
SET #str='';
DECLARE i INT DEFAULT 0;
WHILE i <= 1000 DO
SET #str = SELECT randstring(8);
INSERT INTO Users (user_name)
VALUES(#str);
SET i = i + 1;
END WHILE;
END $$
DELIMITER ;
Presumably, you intend either:
SET #str = randstring(8);
Or:
SELECT #str := randstring(8);
Or:
SET #str = (SELECT #randstring(8));
A SELECT when used as a subquery needs a parentheses before it. However, no subquery is really necessary.

mysql stored procedure declaration throws error on execution

I"m continiously receiving this error when trying to create this stored procedure. I'm trying to write a procedure that splits a comma delimited string. Similar to explode. I feel I'm close.
This is the error
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 'DECLARE start_pos, end_pos INT;
SET start_pos = 1;
SET end_pos = Locat' at line 6
I copied the logic from a SQL Server example and did my best translate it to MySql syntax.
This is the entire procedure from start to finish. I'm hoping a well trained eye can explain why I'm getting an error.
DELIMITER $$
CREATE procedure split_string (in p_string_to_split VARCHAR(255),in p_delimiter CHAR(1) )
BEGIN
DROP TEMPORARY TABLE IF EXISTS split_channel_ids;
CREATE TEMPORARY TABLE split_channel_ids (p_channel_id int);
DECLARE start_pos, end_pos INT;
SET start_pos = 1;
SET end_pos = Locate(p_delimiter, p_string_to_split);
WHILE (start_pos < CHAR_LENGTH(p_string_to_split) + 1) DO
IF (end_pos = 0) THEN
SET end_pos = CHAR_LENGTH(p_string_to_split) + 1;
END IF;
--- INSERT split_channel_ids (p_channel_id)
--- VALUES(SUBSTRING(p_string_to_split, start_pos, end_pos - start_pos)) ;
SET start_pos = end_pos + 1;
SET end_pos = Locate(p_delimiter, p_string_to_split, start_pos);
END WHILE;
-- select * from imob_users;
select * from split_channel_ids;
END $$
DELIMITER ;
DECLARE statements (in MySQL) must be at the beginning of their enclosing BEGIN...END block.
In MS SQL, they can be anywhere; but it is annoying there because they do not have block scope, they have procedure scope, so you can't "re-use" names in independent blocks.

Creating a procedure with multiple parameters in PHPMYADMIN

I am trying to create a procedure to update my database with multiple parameters. Here is my code:
DELIMITER //
CREATE PROCEDURE updateImages (IN stagingID INT, IN streetName VARCHAR(50), IN numberOfImages INT)
BEGIN
DECLARE count INT;
SET count = 1;
WHILE count < (numberOfImages + 1) DO
SET fileName = CONCAT(streetName, ' (mls) (', count, ').jpg');
INSERT INTO images_tbl VALUES
(NULL, stagingID, fileName, 0);
SET count = count + 1;
END WHILE;
END //
DELIMITER ;
PHPMyAdmin is giving me a blank #1193 error with no other information. I've tried to search and implement the resolutions I have found regarding this error, but have not been able to figure it out.
Any ideas would be very welcome. Thanks in advance.
As #Drew pointed out, I omitted a declaration for fileName. Final Code:
DELIMITER //
CREATE PROCEDURE updateImages (IN stagingID INT, IN streetName VARCHAR(50), IN numberOfImages INT)
BEGIN
DECLARE count INT;
DECLARE fileName VARCHAR(100);
SET count = 1;
WHILE count < (numberOfImages + 1) DO
SET fileName = CONCAT(streetName, ' (mls) (', count, ').jpg');
INSERT INTO images_tbl VALUES (NULL, stagingID, fileName, 0);
SET count = count + 1;
END WHILE;
END //
DELIMITER ;

procedure, setting variable, repeat until, substring from one variable, mysql

I am looking for help with my sql procedure.
I would like to substring in loop each username, and alias from two input arguments and add it into table users. I have two procedures.
Sorry for Polish variable names and procedure names.
My first procedure is
CREATE DEFINER=`root`#`localhost` PROCEDURE `dodajZawodnika`(IN `dane` VARCHAR(50), IN `wyswietlanie` VARCHAR(50))
NO SQL
BEGIN
IF (SELECT 1 = 1 from zawodnicy where danezawodnika = dane AND dowyswietlenia=wyswietlanie) THEN
BEGIN
Select id from zawodnicy where danezawodnika=dane AND dowyswietlenia=wyswietlanie;
END;
ELSE
BEGIN
Insert INTO zawodnicy (danezawodnika, dowyswietlenia) VALUES(dane, wyswietlanie);
SELECT last_insert_id() AS ID;
END;
END IF;
END;
My second procedure is
CREATE DEFINER=`root`#`localhost` PROCEDURE `stworzSklad`(IN `dane` VARCHAR(1500), IN `pseudo` VARCHAR(1000))
NO SQL
BEGIN
DECLARE counter INTEGER;
DECLARE zawodnik VARCHAR(1500);
DECLARE pseudonim VARCHAR(1000);
DECLARE zawodnicy VARCHAR(1500);
DECLARE pseudonimy VARCHAR(1000);
DECLARE exit handler for sqlexception
BEGIN
-- ERROR
ROLLBACK;
END;
DECLARE exit handler for sqlwarning
BEGIN
-- WARNING
ROLLBACK;
END;
set counter = 0;
set #zawodnicy = dane;
set #pseudonimy = psuedo;
select #zawodnicy, #pseudonimy;
REPEAT
set zawodnik=(SELECT TRIM(SUBSTRING_INDEX(#zawodnicy, ',', 1)));
set pseudonim=(SELECT TRIM(SUBSTRING_INDEX(#pseudonimy, ',', 1)));
call dodajZawodnika(zawodnik, pseudonim);
SELECT RIGHT(#zawodnicy, TRIM(length(#zawodnicy) - length(SUBSTRING_INDEX(#zawodnicy, ',', 1)) - 1)) into #zawodnicy;
SELECT RIGHT(#pseudonimy, TRIM(length(#pseudonimy) - length(SUBSTRING_INDEX(#pseudonimy, ',', 1)) - 1)) into #pseudonimy;
select zawodnik as 'zawodnik', pseudonim as 'pseudonim', dane as 'dane', pseudo as 'pseudo', #zawodnicy as 'zawodnicy', #pseudonimy as 'pseudonimy';
set counter = counter + 1;
UNTIL (#zawodnicy = '' or counter = 30)
END REPEAT;
select counter;
END
I am fighting with it from about 2 hours.
I would like to use also transaction for this insert.
Please help me with this little problem.
How to make this in proper way?
Now, calling stworzSklad procedure make endless loop (ofc without counter in until condition) and any of user was not inserted in my table.
Cheers!

Error declaring integer variable inside MySQL stored function

I'm getting an error when trying to declare a new stored function in MySQL (Server version: 5.5.13)
Basically, I have a large table which classifies strings depending on how they start. My function takes a string (from user input) and then tells you the classification of that string by searching the database for the classification. It's a bit like a LIKE query, except in reverse as it's the user input that contains the full string and the database contains the string being searched for. Hope that makes sense!
The concept and logic behind it work fine as I've written/developed this in PHP and it works beautifully, however when trying to translate this into a stored function I'm getting an error from MySQL. The code of the function is:
delimiter $
DROP FUNCTION IF EXISTS get_string_class$
CREATE FUNCTION get_string_class(mystring VARCHAR(15))
RETURNS VARCHAR(15)
READS SQL DATA
BEGIN
DECLARE i INT;
SET i = 2;
DECLARE mystringlength INT;
SET mystringlength = LENGTH(mystring);
DECLARE segment VARCHAR(15);
DECLARE String_Class VARCHAR(15);
SET String_Class = NULL;
WHILE i <= mystringlength DO
SET segment = LEFT(mystring, i);
SET String_Class = (SELECT String_Class FROM string_class_list WHERE String_Begins = segment);
IF SELECT FOUND_ROWS() = 1 THEN
RETURN String_Class
END IF;
i = i + 1;
END WHILE;
RETURN String_Class;
END$
delimiter ;
I'm getting this error:
#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
'DECLARE mystringlength INT; SET mystringlength = LENGTH(mystring);
DECLARE segm' at line 10
I've done lots of playing around to trying and work out where I'm going wrong. I've even stripped out the loop altogether to test it, but still get the same error. Does anyone know what I've done wrong where declaring that INT variable? It's probably something incredibly basic...!
Thanks very much in advance.
There were some syntax errors -
One of them is - all declarations must be at the begining of the BEGIN...END clause.
DELIMITER $
DROP FUNCTION IF EXISTS get_string_class$
CREATE FUNCTION get_string_class(mystring VARCHAR(15))
RETURNS VARCHAR(15)
READS SQL DATA
BEGIN
DECLARE i INT;
DECLARE segment VARCHAR(15);
DECLARE String_Class VARCHAR(15);
DECLARE mystringlength INT;
SET i = 2;
SET mystringlength = LENGTH(mystring);
SET String_Class = NULL;
WHILE i <= mystringlength DO
SET segment = LEFT(mystring, i);
SET String_Class = (SELECT String_Class FROM string_class_list WHERE String_Begins = segment);
IF (SELECT FOUND_ROWS()) = 1 THEN
RETURN String_Class;
END IF;
SET i = i + 1;
END WHILE;
RETURN String_Class;
END$
DELIMITER ;
DECLARE part inside stored procedure must be at top and SET and other statemnts starts after that.