MySql - DROP table 'whatever' if exist ELSE create table 'whatever'? - mysql

I simply want to drop the table 'whatever' if it exist and then recreate table 'whatever' in a single query if possible.
DROP TABLE IF EXISTS `whatever` ELSE
CREATE TABLE `whatever`
Any idea ?

CREATE TABLE `whatever` IF NOT EXISTS ELSE TRUNCATE `whatever`
Use TRUNCATE to empty the table and reset cardinality instead of deleting the table and recreating it.

Related

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.

SQL-MYSQL Can't create Database

I always get the error:
CREATE DATABASE bundesliga ERRORCODE 1007 CANT CREATE DATABASE bundesliga, database exists
Here is my code:
CREATE DATABASE bundesliga;
DROP TABLE IF EXISTS Liga;
CREATE TABLE Liga (
);
DROP TABLE IF EXISTS Spiel;
CREATE TABLE Spiel ();
Your Database Bundesliga already exists.
you have to drop your database first and then recreate it.
DROP DATABASE bundesliga;
CREATE DATABASE bundesliga;
DROP TABLE IF EXISTS Liga;
CREATE TABLE Liga (
);
DROP TABLE IF EXISTS Spiel;
CREATE TABLE Spiel ();
or use this
CREATE DATABASE IF NOT EXISTS bundesliga;
and to check if database exist.
SHOW DATABASES LIKE 'bundesliga';
You can use an IF NOT EXISTS clause to prevent the error:
CREATE DATABASE IF NOT EXISTS bundesliga;
If the database already exists, this does nothing. If it doesn't exist, it will be created.
Your database already exists. See error code 1007 here.
Your Database Bundesliga already exists. If you want to recrate you have to drop this before.

Error in event creation using 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.

Create table in MySQL that matches another table?

I am using MySQL. I have a table called EMP, and now I need create one more table (EMP_TWO) with same schema, same columns, and same constraints. How can I do this?
To create a new table based on another tables structure / constraints use :
CREATE TABLE new_table LIKE old_table;
To copy the data across, if required, use
INSERT INTO new_table SELECT * FROM old_table;
Create table docs
Beware of the notes on the LIKE option :
Use LIKE to create an empty table based on the definition of another
table, including any column attributes and indexes defined in the
original table:
CREATE TABLE new_table LIKE original_table; The copy is created using the same
version of the table storage format as the original table. The SELECT
privilege is required on the original table.
LIKE works only for base tables, not for views.
CREATE TABLE ... LIKE does not preserve any DATA DIRECTORY or INDEX
DIRECTORY table options that were specified for the original table, or
any foreign key definitions.
If you want to copy only Structure then use
create table new_tbl like old_tbl;
If you want to copy Structure as well as data then use
create table new_tbl select * from old_tbl;
Create table in MySQL that matches another table?
Ans:
CREATE TABLE new_table AS SELECT * FROM old_table;
Why don't you go like this
CREATE TABLE new_table LIKE Select * from Old_Table;
or You can go by filtering data like this
CREATE TABLE new_table LIKE Select column1, column2, column3 from Old_Table where column1 = Value1;
For having Same constraint in your new table first you will have to create schema then you should go for data for schema creation
CREATE TABLE new_table LIKE Some_other_Table;
by only using the following command on MySQL command line 8.0 the following ERROR is displayed
[ mysql> select * into at from af;]
ERROR 1327 (42000): Undeclared variable: at
so just to copy the exact schema without the data in it you can use the create table with like statement as follows:
create table EMP_TWO like EMP;
and to copy table along with the data use:
create table EMP_TWO select * from EMP;
to only copy tables data after creating an empty table:
insert into EMP_TWO select * from EMP;

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.