Temporary Procedure define variable issue - mysql

I'm trying out MySQL procedures for the first time, however I can't figure out how to define the variable #index_ids for the life of me. It really doesn't like the SET.
CREATE PROCEDURE #indextemp
BEGIN
SET #index_ids = (SELECT DISTINCT index_id FROM visibility_index_processing_queue WHERE process_id IS NOT NULL);
SELECT #index_ids;
END

Problem is in CREATE PROCEDURE syntax, not in setting variable. You just have to add parentheses after procedure name. Here's working sample
delimiter $
CREATE PROCEDURE indextemp()
BEGIN
SET #index_ids = (SELECT DISTINCT index_id FROM visibility_index_processing_queue WHERE process_id IS NOT NULL);
SELECT #index_ids;
END$
delimiter ;
Sometimes use of delimiter character in procedure body can cause problems too. That's why I set delimiter to $ before creating procedure and revert it to default ; after I'm done.
Also notice that I have removed # from your procedure name. In sql # is used to insert comments. If for some reason you really want to use it in your name you have to do it like that
CREATE PROCEDURE `#indextemp`()

Related

MySQL Call procedure inside function for count

Is it possible to use a procedure inside a function? For example, I would like to gather all my rows related to an id but I would also like to count the rows and use it in a select statement. This is not working:
drop procedure if exists relatives;
create procedure relatives(in parent int(11),out counted int(11))
begin
set counted=(select count(*) from category where related=parent);
end;
drop function if exists relatives_count;
create function relatives_count(parent parent(11)) returns int(11)
begin
declare count int(11);
call relatives(parent,counted);
return counted;
end;
So that I can use the count
select relatives_count(id) from category
This is just for curiosity purposes. It may look senseless since I can just call a single select query and get the same results but I want to know how I can use my procedure out variable in a function.
Yes, a MySQL FUNCTION can call a MySQL PROCEDURE.
But... the operations the procedure performs will be limited to the operations allowed by a function. (We can't use a procedure to workaround the limitations placed on a function.)
"is not working" is so nebulously vague as to be practically useless in debugging the issue. What exact behavior is being observed?
My suspicion is that the SQL statements shown are failing, because there is no override for the default statement delimiter.
Also, parent(11) is not a valid datatype.
Be aware that when an identifier for a column in a SQL statement in a MySQL stored program matches an identifier used for an argument or local variable, MySQL follows a rule about which (the column name or the variable) that is being referenced.
Best practice is to adopt a naming convention for arguments and local variables that do not match column names, and to qualify all column references with a table name or table alias.
Personally, I use a prefix for arguments and local variables (a for argument, l for local, followed by a datatype i for integer, d for date/datetime, n for decimal, ...
DELIMITER $$
DROP PROCEDURE IF EXISTS relatives$$
CREATE PROCEDURE relatives(IN ai_parent INT(11),OUT ai_counted INT(11))
BEGIN
SELECT COUNT(*)
INTO ai_counted
FROM category c
WHERE c.related = ai_parent
;
END$$
DROP FUNCTION IF EXISTS relatives_count$$
CREATE FUNCTION relatives_count(ai_parent INT(11))
RETURNS INT(11)
BEGIN
DECLARE li_counted INT(11);
CALL relatives(ai_parent,li_counted);
RETURN li_counted;
END$$
DELIMITER ;
Please identify the exact behavior you observe. Error message when creating the procedure? Error message when executing the function? Unexpected behavior. That's much more precise and informative than telling us something "is not working".

mysql where clause doesn't work

I am writing a stored procedure in mysql which simply returns the row with ID provided or return all table when no ID is provided.
CREATE DEFINER=`root`#`localhost` PROCEDURE `SLICE_GET`(`slice_id` int)
BEGIN
SELECT *
FROM `thesis_db`.`SLICE_INFO`
WHERE (SLICE_ID = `slice_id` OR `slice_id` IS NULL);
END
I have used the same idea in ms-sql for years yet it doesn't seem to work for mysql since no matter which ID is passed, the procedure returns entire table.
What am I missing here ?
This is a way to write procedures in mysql
DELIMITER $$
CREATE PROCEDURE `name of procedure` (x CHAR(1), D1 DATE, D2 DATE)
BEGIN
SELECT name of columns you want to display
FROM table name
WHERE SLICE_ID= x
OR SLICE_ID IS NULL;
END
$$
Note: Moreover mysql is not case sensitive means all caps or all small will not effect it.
delimiter is used to:
If you use the mysql client program to define a stored program containing semicolon characters, a problem arises.
By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server.

how to call multiple columns in a stored procedure

I'm new to stored procedure and I don't know much.
I'm testing with an example. Could you help me?
Here is my stored procedure
DELIMITER $$
DROP PROCEDURE IF EXISTS dictionarytable$$
CREATE PROCEDURE dictionarytable(id VARCHAR(20),name
VARCHAR(20),work VARCHAR(20),place VARCHAR(20),mobileno
VARCHAR(20),bike VARCHAR(20),car VARCHAR(20),homeno
VARCHAR(20),dictionaytype VARCHAR(20),meaning VARCHAR(20),sentence
VARCHAR(20),antonym VARCHAR(20),synonym VARCHAR(20))
BEGIN
select
id,name,work,place,mobileno,bike,car,homeno,dictionaytype,meaning,sentence,antonym,synonym
from dictionary INTO dictionarytable; END $$
DELIMITER ;
I wanted id,name,13 columns from dictionary(table) to be called in stored procedure dictionarytable
the query in the Begin is wrong could you specify a query to display all 13 columns
You cannot pass field values INTO the procedure, you can pass them INTO user variables, declared variables or OUT paramaters. Note, that only one record can be passed when INTO clause is used. For example:
SET #var1 = NULL;
SELECT column1 INTO #var1 FROM table;
If you want to copy more then one record, then you can use INSERT INTO...SELECT statement to copy data-set to second table. For example:
INSERT INTO table2 SELECT column1 FROM table;
Also, if you want to use variables or parameters as identifiers (field names in your case), then you should use prepared statements.

mysql stored procedure call unable to access parameter value

I have a stored procedure named create_new_db(p VARCHAR(45)) on mysqldb. The syntax is as follows.
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `create_new_db`( p VARCHAR(45))
BEGIN
CREATE SCHEMA IF NOT EXISTS p DEFAULT CHARACTER SET latin1 ;
-- -----------------------------------------------------
-- Table `p`.`events`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS p.events ( yada, yada, ...)
When I call the stored procedure using the
Call mysqldb.create_new_db('new_db_name');
The procedure executes, the database and tables get created but the parameter i am passing in is NOT being accessed. The database that is created is named p and not the name paramter that i pass in to the procedure
I have tried assigning the paramater to a global variable within the script
#P = p;
I can then see that the parameter name that i am passing into the procedure is getting into the stored procedure but how come it not working ??
I am likely missing something obvious here but ... some help would be appreciated.
You can't create dynamic sql like that. You must use EXECUTE IMMEDIATE 'some dynamic sql stmt'
You pass a string to it, so build your sql up in your stored proc, like this:
EXECUTE IMMEDIATE concat('CREATE SCHEMA IF NOT EXISTS ', p, ' DEFAULT CHARACTER SET latin1');
and similar for your other CREATE statements

How to use DROP TABLE IF EXISTS in a MySQL Stored Procedure

I want to know how to use DROP TABLE IF EXISTS in a MySQLstored procedure.
I'm writing a rather long mySQL Stored Procedure that will do a bunch of work and then load up a temp table with the results. However, I am having trouble making this work.
I've seen a few ways to do the temp table thing. Basically, you either create the temp table, work on it, and then drop it at the end ... or you drop it if it exists, create it, and then do your work on it.
I prefer the second method so that you always start of clean, and it's a built-in check for the table's existence. However, I can't seem to get it to work:
Here are my examples:
This Works:
DELIMITER//
DROP PROCEDURE IF EXISTS pTest//
CREATE PROCEDURE pTest()
BEGIN
CREATE TEMPORARY TABLE tblTest (
OrderDate varchar(200)
);
DROP TEMPORARY TABLE tblTest;
END//
DELIMITER ;
CALL pTest();
This Works:
DELIMITER//
DROP PROCEDURE IF EXISTS pTest//
CREATE PROCEDURE pTest()
BEGIN
DROP TEMPORARY TABLE tblTest;
CREATE TEMPORARY TABLE tblTest (
OrderDate varchar(200)
);
END//
DELIMITER ;
CALL pTest();
This does not:
DELIMITER//
DROP PROCEDURE IF EXISTS pTest//
CREATE PROCEDURE pTest()
BEGIN
DROP TEMPORARY TABLE IF EXISTS tblTest;
CREATE TEMPORARY TABLE tblTest (
OrderDate varchar(200)
);
END//
DELIMITER ;
CALL pTest();
The first 2 work, but if that table exists (like if the procedure didn't finish or something), it'll obviously end with a "Table tblTest does not exist" error. The non-working example is what I'm looking for -- drop the table if its there and then recreate it so that I can start clean.
It feels like it's the "IF EXISTS" making this thing fail. I've copied code from all sorts of sites that do things very similar and in no case can I get a "DROP TABLE IF EXISTS..." to work. Ever.
Dev Server: mySQL Server version: 5.1.47-community
Prod Server: mySQL Server version: 5.0.45-log
We can't change db versions (DBAs won't allow it), so I'm stuck on what I have. Is this a bug in mySQL or in the Procedure?
Thanks.
It's an old question but it came up as I was looking for DROP TABLE IF EXISTS.
Your non-working code did not work on my MySQL 5.1.70 server.
All I had to do was add a space between DELIMITER and // on the first line, and everything worked fine.
Working code:
DELIMITER //
DROP PROCEDURE IF EXISTS pTest//
CREATE PROCEDURE pTest()
BEGIN
DROP TEMPORARY TABLE IF EXISTS tblTest;
CREATE TEMPORARY TABLE tblTest (
OrderDate varchar(200)
);
END//
DELIMITER ;
I don't know why this is not working for you,but you should be able to work around the issue using a continue handler. If you put the DROP TABLE statement into it's own BEGIN...END block you can use a continue handler to ignore the error if the table does not exist.
Try this:
DELIMITER //
DROP PROCEDURE IF EXISTS pTest //
CREATE PROCEDURE pTest()
BEGIN
BEGIN
DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02' BEGIN END;
DROP TEMPORARY TABLE tblTest;
END;
CREATE TEMPORARY TABLE tblTest (
OrderDate varchar(200)
);
END //
DELIMITER ;
CALL pTest();
I also had the same problem. It seems MySQL doesn't like to check if the table exists on some versions or something. I worked around the issue by querying the database first, and if I found a table I dropped it. Using PHP:
$q = #mysql_query("SELECT * FROM `$name`");
if ($q){
$q = mysql_query("DROP TABLE `$name`");
if(!$q) die('e: Could not drop the table '.mysql_error());
}
You suppress the error in the first query with the # symbol, so you don't have an interfering error, and then drop the table when the query returns false.
I recommend to add new line
SET sql_notes = 0// before DROP PROCEDURE IF EXISTS get_table //
Otherwise it will show warning PROCEDURE does not exists.