在MySQL中创建表变量

发布于 2024-08-06 17:51:17 字数 165 浏览 5 评论 0原文

我需要一个表变量来存储 MySQL 过程中表中的特定行。 例如声明@tb table (id int,name varchar(200))

这可能吗?如果是的话怎么办?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

亢潮 2024-08-13 17:51:17

MySQL 中不存在它们吗?只需使用临时表:

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 .... */

来自 MySQL

“您可以使用 TEMPORARY 关键字
创建表时。临时的
表仅对当前可见
连接,并且被丢弃
连接时自动
关闭。这意味着两个不同的
连接可以使用相同的临时
表名不冲突
彼此或与现有的
同名的非 TEMPORARY 表。
(现有表将被隐藏,直到
临时表被删除。)”

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.)"

冰火雁神 2024-08-13 17:51:17

也许临时表可以满足您的要求。

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; 

来自 forge.mysql.com。另请参阅本文的临时表部分。

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.

来世叙缘 2024-08-13 17:51:17

回答你的问题:不,MySQL 不支持表类型变量,其方式与 SQL Server (http://msdn.microsoft.com/en-us/library/ms188927.aspx) 提供的方式相同。 Oracle 提供了类似的功能,但将它们称为游标类型而不是表类型 (http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems012.htm)。

根据您的需要,您可以使用临时表来模拟 MySQL 中的表/游标类型变量,其方式类似于 Oracle 和 SQL Server 提供的方式。

然而,临时表方法和表/游标类型变量方法之间有一个重要的区别,它对性能有很大的影响(这就是为什么 Oracle 和 SQL Server 在临时表提供的功能之上提供此功能的原因)表)。

具体来说:表/游标类型变量允许客户端在客户端整理多行数据并将它们作为存储过程或准备语句的输入发送到服务器。这消除了发送每个单独行的开销,而是为一批行支付一次开销。当您尝试导入大量数据时,这可能会对整体性能产生重大影响。

一个可能的解决方法:

您可能想要尝试创建一个临时表,然后使用 LOAD DATA (http://dev.mysql.com/doc/refman/5.1/en/load-data.html) 命令来将数据流式传输到临时表中。然后,您可以将临时表的名称传递到存储过程中。这仍然会导致对数据库服务器的两次调用,但如果您移动足够多的行,则可能会节省费用。当然,只有当您更新目标表时在存储过程中执行某种逻辑时,这才真正有用。如果没有,您可能只想将数据直接加载到目标表中。

TO answer your question: no, MySQL does not support Table-typed variables in the same manner that SQL Server (http://msdn.microsoft.com/en-us/library/ms188927.aspx) provides. Oracle provides similar functionality but calls them Cursor types instead of table types (http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems012.htm).

Depending your needs you can simulate table/cursor-typed variables in MySQL using temporary tables in a manner similar to what is provided by both Oracle and SQL Server.

However, there is an important difference between the temporary table approach and the table/cursor-typed variable approach and it has a lot of performance implications (this is the reason why Oracle and SQL Server provide this functionality over and above what is provided with temporary tables).

Specifically: table/cursor-typed variables allow the client to collate multiple rows of data on the client side and send them up to the server as input to a stored procedure or prepared statement. What this eliminates is the overhead of sending up each individual row and instead pay that overhead once for a batch of rows. This can have a significant impact on overall performance when you are trying to import larger quantities of data.

A possible work-around:

What you may want to try is creating a temporary table and then using a LOAD DATA (http://dev.mysql.com/doc/refman/5.1/en/load-data.html) command to stream the data into the temporary table. You could then pass them name of the temporary table into your stored procedure. This will still result in two calls to the database server, but if you are moving enough rows there may be a savings there. Of course, this is really only beneficial if you are doing some kind of logic inside the stored procedure as you update the target table. If not, you may just want to LOAD DATA directly into the target table.

在你怀里撒娇 2024-08-13 17:51:17

MYSQL 8 在某种程度上做到了:

MYSQL 8 支持 JSON 表,因此您可以将结果加载到 JSON 变量中,并使用 JSON_TABLE() 命令从该变量中进行选择。

MYSQL 8 does, in a way:

MYSQL 8 supports JSON tables, so you could load your results into a JSON variable and select from that variable using the JSON_TABLE() command.

为你拒绝所有暧昧 2024-08-13 17:51:17

如果您不想将表存储在数据库中,那么 @Evan Todd 已经提供了临时表解决方案。

但是,如果您需要其他用户使用该表并希望存储在数据库中,那么您可以使用以下过程。

创建以下“存储过程”:

———————————

DELIMITER $

USE `test`$

DROP PROCEDURE IF EXISTS `sp_variable_table`$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_variable_table`()
BEGIN

SELECT CONCAT(‘zafar_’,REPLACE(TIME(NOW()),’:',’_')) INTO @tbl;

SET @str=CONCAT(“create table “,@tbl,” (pbirfnum BIGINT(20) NOT NULL DEFAULT ’0′, paymentModes TEXT ,paymentmodeDetails TEXT ,shippingCharges TEXT ,shippingDetails TEXT ,hypenedSkuCodes TEXT ,skuCodes TEXT ,itemDetails TEXT ,colorDesc TEXT ,size TEXT ,atmDesc TEXT ,promotional TEXT ,productSeqNumber VARCHAR(16) DEFAULT NULL,entity TEXT ,entityDetails TEXT ,kmtnmt TEXT ,rating BIGINT(1) DEFAULT NULL,discount DECIMAL(15,0) DEFAULT NULL,itemStockDetails VARCHAR(38) NOT NULL DEFAULT ”) ENGINE=INNODB DEFAULT CHARSET=utf8″);
PREPARE stmt FROM @str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT ‘Table has been created’;
END$

DELIMITER ;

———————————————–

现在您可以执行此过程来创建变量名称表,如下所示-

调用 sp_variable_table();

您可以在执行以下命令后检查新表 -

use test;show rows like '%zafar%'; — test 这里是“数据库”名称。

您还可以在以下路径查看更多详细信息 -

http:// mydbsolutions.in/how-can-create-a-table-with-variable-name/

If you don't want to store table in database then @Evan Todd already has been provided temporary table solution.

But if you need that table for other users and want to store in db then you can use below procedure.

Create below ‘stored procedure’:

————————————

DELIMITER $

USE `test`$

DROP PROCEDURE IF EXISTS `sp_variable_table`$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_variable_table`()
BEGIN

SELECT CONCAT(‘zafar_’,REPLACE(TIME(NOW()),’:',’_')) INTO @tbl;

SET @str=CONCAT(“create table “,@tbl,” (pbirfnum BIGINT(20) NOT NULL DEFAULT ’0′, paymentModes TEXT ,paymentmodeDetails TEXT ,shippingCharges TEXT ,shippingDetails TEXT ,hypenedSkuCodes TEXT ,skuCodes TEXT ,itemDetails TEXT ,colorDesc TEXT ,size TEXT ,atmDesc TEXT ,promotional TEXT ,productSeqNumber VARCHAR(16) DEFAULT NULL,entity TEXT ,entityDetails TEXT ,kmtnmt TEXT ,rating BIGINT(1) DEFAULT NULL,discount DECIMAL(15,0) DEFAULT NULL,itemStockDetails VARCHAR(38) NOT NULL DEFAULT ”) ENGINE=INNODB DEFAULT CHARSET=utf8″);
PREPARE stmt FROM @str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SELECT ‘Table has been created’;
END$

DELIMITER ;

———————————————–

Now you can execute this procedure to create a variable name table as per below-

call sp_variable_table();

You can check new table after executing below command-

use test;show tables like ‘%zafar%’; — test is here ‘database’ name.

You can also check more details at below path-

http://mydbsolutions.in/how-can-create-a-table-with-variable-name/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文