Error in event creation using MySQL - mysql

Am using the below code to create an EVENT in MYSQL. In this time i want to drop and create a table using a query.
Drop Event if exists EVT_UP_TIMESHEET;
CREATE EVENT EVT_UP_TIMESHEET
ON SCHEDULE EVERY '1' Day
STARTS '2012-08-01 12:00:00'
DO
Drop table if exists tbl_temp;
create table tbl_temp as ( SELECT e.userid AS Employee_ID,
e.memo AS Employee_Name,
e.Department AS Department,
.....
It returns the following error:
ERROR : Table tbl_temp already exists.
Please help me to do this.

Use CREATE TABLE IF NOT EXISTS tbl_temp instead of create table tbl_temp
Or to delete the table you can use TRUNCATE TABLE instead of DROP TABLE and to create you can use INSERT...SELECT instead of CREATE TABLE.

As a workaround - try to use TRUNCATE TABLE and INSERT...SELECT statements instead of DROP/CREATE TABLE.

Related

How to select content from a table into a new table in SQL stored procedures?

I was trying to write a procedure and needed to copy output_1 table into a new one.
This procedure :
BEGIN
SELECT * INTO newtable FROM output_1;
END
returns the following error :Undeclared variable: newtable
I thought it would create a new table and all its columns automatically.
How do I SELECT multiple columns of a table INTO a new table using a stored procedure?
EDIT :
In stored procedures, when you want to use a table to store data temporarily, you should consider using temporary tables.
Typically, if you try to store a table in a variable, you will get a multiple rows error ; in this case, temporary tables can replace variables.
CREATE TEMPORARY TABLE new_table AS SELECT * FROM output_1;
You cannot select into a table. You possibly intended
create table newtable as select * from output_1;
https://dev.mysql.com/doc/refman/8.0/en/create-table-select.html

How to create a table that lists all the names in one table and counts the number of times it appears in another one?

I have to create a table named vecesCarcel which whenever I insert a name, it automatically adds another cell with the number of times the name appears in another table. So far I've tried with triggers this, but without result:
USE lordfarquaad;
CREATE TABLE IF NOT EXISTS vecesCarcel(
nombrePersonaje VARCHAR(10),
veces INTEGER(5) UNSIGNED)
ENGINE=InnoDB;
ALTER TABLE vecesCarcel
ADD CONSTRAINT vecesCarcelFK1 FOREIGN KEY(nombrePersonaje)
REFERENCES personajes(nombrePersonaje)
ON DELETE CASCADE ON UPDATE CASCADE;
USE lordfarquaad;
DELIMITER $$
CREATE PROCEDURE checkvecescarcel(IN nombre VARCHAR(10),OUT veces INT(5))
BEGIN
SET veces=(SELECT COUNT(*) FROM historiales WHERE nombrePersonaje=nombre);
END
$$
CREATE TRIGGER vecesCarcel_Insert BEFORE INSERT ON vecesCarcel FOR EACH ROW
BEGIN
CALL checkvecescarcel(NEW.nombrePersonaje,NEW.veces);
END;
$$
If you want to use a trigger, you have to set the new.veces-value inside the trigger:
CREATE TRIGGER vecesCarcel_Insert BEFORE INSERT ON vecesCarcel FOR EACH ROW
SET new.veces=(SELECT COUNT(*) FROM historiales
WHERE nombrePersonaje=NEW.nombrePersonaje);
You might want to create an on update-trigger, too (same code, so you can aswell put select count(*)... in a function and use set new.veces = myfnct(new.nombrepersonaje)).
But keep in mind your count will not update itself if you change anything in the table historiales (e.g. add another entry with the name in the list). So, depending on your setup, and if your historiales-table can change, or if you just might want to try a different approach, you can try a view:
create view vecesCarcelView as
select nombrePersonaje,
(select count(*)
from historiales
where vecesCarcel.nombrePersonaje=historiales.nombrePersonaje) as veces
from vecesCarcel;
(If you don't care so much about the order, you can do this with a left join and a group by too; and you could actually use the view with the whole personajes-table to display the count for all known names.)

MySQL query TRUNCATE ERROR

i have query like this and dont know why it gives me the error. I want to create the table if it is not already created, if it is created, then truncate it and then insert into that that table the following
CREATE TABLE IF NOT EXISTS
`(temp)_v5_userInfo_Netsprint_Data_import`
(
onlineId VARCHAR(255),
paramId INT,
paramValue INT
)
TRUNCATE TABLE
`(temp)_v5_userInfo_Netsprint_Data_import`
INSERT INTO
`(temp)_v5_userInfo_Netsprint_Data_import`
SELECT
`ui`.`onlineId`, `uin`.`paramId`, `uin`.`paramValue`
FROM
`(temp)v5_userInfo_COLD` `ui`
JOIN
`v5_(readOnly)userInfo_number` `uin`
ON
`uin`.`userId` = `ui`.`id`
;
first two statements are missing delimiter ";"
add them and it will work.
There are two factors in this. First, as #krishKM says, you have missing semicolons. The statements should be:
CREATE TABLE IF NOT EXISTS `(temp)_v5_userInfo_Netsprint_Data_import`
(
onlineId VARCHAR(255),
paramId INT,
paramValue INT
);
TRUNCATE TABLE `(temp)_v5_userInfo_Netsprint_Data_import`;
INSERT INTO `(temp)_v5_userInfo_Netsprint_Data_import`
SELECT `ui`.`onlineId`,
`uin`.`paramId`,
`uin`.`paramValue`
FROM `(temp)v5_userInfo_COLD` `ui`
JOIN `v5_(readOnly)userInfo_number` `uin` ON `uin`.`userId` = `ui`.`id`;
second, verify the privileges for the user that will execute this statements. TRUNCATE requires DROP privilege since MySQL 5.1.6
My guess is that your user has DATA + CREATE privileges, but they are not enough.
If adding drop privileges is a showstopper, one possible workaround would be to execute
DELETE FROM `(temp)_v5_userInfo_Netsprint_Data_import`;
Which is, of course, slower.

Use If exists for select statement in mysql

I am creating a view and written the below code snippet :
CREATE OR REPLACE VIEW vclPersonData
AS
SELECT * FROM phone_data UNION
SELECT * FROM Address
I get an error if the table doesn't exists, to come overthat i used If Exists but it too doesn't works for me.
Any help is thankful.
Thanks in Advance.
You'll need two steps in your script:
CREATE TABLE IF NOT EXISTS
CREATE VIEW AS SELECT * FROM TABLE
If the table exists, step 1 will be harmless. If the table does not exist, step 1 will create it and step 2 will create an empty view.
If you only want the view to be created IF the table exist, check the existance of the table before:
BEGIN
SELECT 1 FROM TABLE;
CREATE VIEW AS SELECT * FROM TABLE
COMMIT

MySql - Create Table If Not Exists Else Truncate?

Here is the updated question:
the current query is doing something like:
$sql1 = "TRUNCATE TABLE fubar";
$sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu";
The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet.
Is my only option to do the CREATE TABLE, run the TRUNCATE TABLE, and then fill the table? (3 separate queries)
original question was:
I've been having a hard time trying to figure out if the following is possible in MySql without having to write block sql:
CREATE TABLE fubar IF NOT EXISTS ELSE TRUNCATE TABLE fubar
If I run truncate separately before the create table, and the table doesn't exist, then I get an error message. I'm trying to eliminate that error message without having to add any more queries.
This code will be executed using PHP.
shmuel613, it would be better to update your original question rather than replying. It's best if there's a single place containing the complete question rather than having it spread out in a discussion.
Ben's answer is reasonable, except he seems to have a 'not' where he doesn't want one. Dropping the table only if it doesn't exist isn't quite right.
You will indeed need multiple statements. Either conditionally create then populate:
CREATE TEMPORARY TABLE IF NOT EXISTS fubar ( id int, name varchar(80) )
TRUNCATE TABLE fubar
INSERT INTO fubar SELECT * FROM barfu
or just drop and recreate
DROP TABLE IF EXISTS fubar
CREATE TEMPORARY TABLE fubar SELECT id, name FROM barfu
With pure SQL those are your two real classes of solutions. I like the second better.
(With a stored procedure you could reduce it to a single statement. Something like: TruncateAndPopulate(fubar) But by the time you write the code for TruncateAndPopulate() you'll spend more time than just using the SQL above.)
You could do the truncate after the 'create if not exists'.
That way it will always exist... and always be empty at that point.
CREATE TABLE fubar IF NOT EXISTS
TRUNCATE TABLE fubar
execute any query if table exists.
Usage: call Edit_table(database-name,table-name,query-string);
Procedure will check for existence of table-name under database-name and will execute query-string if it exists.
Following is the stored procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS `Edit_table` $$
CREATE PROCEDURE `Edit_table` (in_db_nm varchar(20), in_tbl_nm varchar(20), in_your_query varchar(200))
DETERMINISTIC
BEGIN
DECLARE var_table_count INT;
select count(*) INTO #var_table_count from information_schema.TABLES where TABLE_NAME=in_tbl_nm and TABLE_SCHEMA=in_db_nm;
IF (#var_table_count > 0) THEN
SET #in_your_query = in_your_query;
#SELECT #in_your_query;
PREPARE my_query FROM #in_your_query;
EXECUTE my_query;
ELSE
select "Table Not Found";
END IF;
END $$
DELIMITER ;
More on Mysql
how about:
DROP TABLE IF EXISTS fubar;
CREATE TABLE fubar;
Or did you mean you just want to do it with a single query?
OK then, not bad. To be more specific, the current query is doing something like:
$sql1 = "TRUNCATE TABLE fubar";
$sql2 = "CREATE TEMPORARY TABLE IF NOT EXISTS fubar SELECT id, name FROM barfu";
The first time the method containing this is run, it generates an error message on the truncate since the table doesn't exist yet.
Is my only option to do the "CREATE TABLE", run the "TRUNCATE TABLE", and then fill the table? (3 separate queries)
PS - thanks for responding so quickly!
If you're using PHP, use mysql_list_tables to check that the table exists before TRUNCATE it.