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

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

Related

Create Trigger inside stored procedure in mysql

I want to create an trigger inside an procedure. but after some research I got to know that it is not possible. can u suggest me another way I can achieve the below actions. (I cant share exact data and queries due to some reason. please refer similar queries.)
What I want
I have created an temporary table containing data i need.
eg. CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;
I want to inset data in table table2 when data is inserted in temp1, which i can achieve by creating a TRIGGER. but the problem is I want to give a value in table2 which will be dynamic and will be taken from nodejs backend. so i created a PROCEDURE which takes parameter neededId. but i cant created trigger inside a procedure. is their any other way i can achieve this?
Procedure I Created
here neededId is the foreign key I get from backend to insert
DELIMITER $$
USE `DB`$$
CREATE PROCEDURE `MyProcedure` (IN neededID int)
BEGIN
DROP TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;
DROP TRIGGER IF EXISTS myTrigger;
CREATE TRIGGER myTrigger AFTER INSERT ON temp1 FOR EACH ROW
BEGIN
INSERT into table2("value1", "value2", neededId);
END;
END$$
DELIMITER ;
SQL Statements Not Permitted in Stored Routines
Generally, statements not permitted in SQL prepared statements are also not permitted in stored programs. ... Exceptions are SIGNAL, RESIGNAL, and GET DIAGNOSTICS, which are not permissible as prepared statements but are permitted in stored programs.
SQL Syntax Permitted in Prepared Statements
CREATE TRIGGER is not listed.
Finally: the trigger cannot be created in stored procedure, function, prepared statement, trigger or event procedure.
In MySQL, you can't create a trigger for a temporary table, regardless of whether you do it in a stored procedure or not.
https://dev.mysql.com/doc/refman/8.0/en/create-trigger.html says:
The trigger becomes associated with the table named tbl_name, which must refer to a permanent table. You cannot associate a trigger with a TEMPORARY table or a view.
I assume the same is true of MariaDB. It's not clear from your question which one you use. You say MySQL at first, but you tagged the question mariadb. Be aware that these are not the same database product, and they are not necessarily compatible.
Here's a demo of the error, tested on MySQL 8.0.28:
mysql> create temporary table t ( i int );
mysql> create trigger t before insert on t for each row set NEW.i = 42;
ERROR 1361 (HY000): Trigger's 't' is view or temporary table
So in your case, you cannot use a trigger for the temporary table. You'll have to think of a different way to implement inserts to your second table.

Join if temporary table exists

Briefly,
How I create my temporary table
CREATE TEMPORARY TABLE _tmp_table SELECT * FROM db1;
then,
# if tmp_table does exist
SELECT db2.*, _tmp_table.* FROM 'db2' LEFT OUTER JOIN _tmp_table ON _tmp_table.key = db2.id;
# if tmp_table does NOT exist
SELECT db2.* FROM db2;
How can I make only one query to deal with my temporary table existing or not?
Env: Mysql 5.5.15.
You cannot do it in one statement.
You need an assurance that the table you are joining existed or else you will be getting an exception. I rather create a stored procedure for that which checks for table existence.

Mysql Procedure Get Data From Temporary Table

I have create mysql store procedure created a temporary table on it.Now i want to fetch all the data from temp table.How can i do this?Please help me.
Call your_sp_name; /* so data could insert into temp table*/
SELECT * FROM temp_table_name;

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.