Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table variable in MySQL

I need a table variable to store the particular rows from the table within the MySQL procedure. E.g. declare @tb table (id int,name varchar(200))

Is this possible? If yes how?

like image 803
ANIL MANE Avatar asked Oct 06 '09 10:10

ANIL MANE


People also ask

How do I add a variable to a table in MySQL?

set @variable= @variable1+@variable2 INSERT INTO table (column) VALUES(@variable); INSERT INTO table (column) VALUES('variable');

What is a table variable?

Definition. The table variable is a special type of the local variable that helps to store data temporarily, similar to the temp table in SQL Server. In fact, the table variable provides all the properties of the local variable, but the local variables have some limitations, unlike temp or regular tables.


2 Answers

They don't exist in MySQL do they? Just use a temp table:

CREATE PROCEDURE my_proc () BEGIN   CREATE TEMPORARY TABLE TempTable (myid int, myfield varchar(100));  INSERT INTO TempTable SELECT tblid, tblfield FROM Table1;   /* Do some more stuff .... */ 

From MySQL here

"You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed. This means that two different connections can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.)"

like image 116
Preet Sangha Avatar answered Sep 19 '22 09:09

Preet Sangha


Perhaps a temporary table will do what you want.

CREATE TEMPORARY TABLE SalesSummary ( product_name VARCHAR(50) NOT NULL , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00 , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00 , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0 ) ENGINE=MEMORY;  INSERT INTO SalesSummary (product_name, total_sales, avg_unit_price, total_units_sold) SELECT    p.name   , SUM(oi.sales_amount)   , AVG(oi.unit_price)   , SUM(oi.quantity_sold) FROM OrderItems oi INNER JOIN Products p     ON oi.product_id = p.product_id GROUP BY p.name;  /* Just output the table */ SELECT * FROM SalesSummary;  /* OK, get the highest selling product from the table */ SELECT product_name AS "Top Seller" FROM SalesSummary ORDER BY total_sales DESC LIMIT 1;  /* Explicitly destroy the table */ DROP TABLE SalesSummary;  

From forge.mysql.com. See also the temporary tables piece of this article.

like image 28
Ewan Todd Avatar answered Sep 19 '22 09:09

Ewan Todd