将数组传递给 MySQL 存储例程

Pass array to MySQL stored routine(将数组传递给 MySQL 存储例程)
本文介绍了将数组传递给 MySQL 存储例程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要将字符串数组作为参数传递给 MySQL 存储例程.该数组可能很长,并且其元素数量不固定.然后我想将字符串值放入一个包含一列的内存表中,以便我可以处理数据.我不知道这是否可以在 MySQL 中完成.也许需要一些肮脏的解决方法.

I need to pass an array of strings as parameter to a MySQL stored routine. The array could be long and its number of elements is not fixed. I then want to put the string values into an in-memory table with one column, so I can work with the data. I don't know if this can be done in MySQL. Maybe dirty workarounds are needed.

例如,我有字符串值:

Banana, Apple, Orange

现在我想从我的 MySQL Fruits 表中获取有关这些水果的数据.伪代码:

Now I want to get data on these fruits from my MySQL Fruits table. Pseudo code:

create function GetFruits(Array fruitArray) 
   declare @temp table as
      fruitName varchar(100)
   end

   @temp = convert fruitArray to table
   select * from Fruits where Name in (select fruitName from @temp)
end

Microsoft SQL Server 允许您使用 TEXT 数据类型并将数组作为 XML 字符串提交,从而快速创建内存表.但是,我认为 MySQL 中不可能使用这种技术.

Microsoft SQL Server allows you to use the TEXT datatype and submit the array as an XML string, swiftly creating the in-memory table. However, I don't think that technique is possible in MySQL.

任何有关如何执行此操作的帮助将不胜感激!

Any help on how to do this would be appreciated!

推荐答案

您可以在列表中传递一个字符串并使用 prepared statements 运行查询,例如-

You can pass a string with your list and use a prepared statements to run a query, e.g. -

DELIMITER $$

CREATE PROCEDURE GetFruits(IN fruitArray VARCHAR(255))
BEGIN

  SET @sql = CONCAT('SELECT * FROM Fruits WHERE Name IN (', fruitArray, ')');
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;

END
$$

DELIMITER ;

使用方法:

SET @fruitArray = '\'apple\',\'banana\'';
CALL GetFruits(@fruitArray);

这篇关于将数组传递给 MySQL 存储例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Can#39;t Create Entity Data Model - using MySql and EF6(无法创建实体数据模型 - 使用 MySql 和 EF6)
MySQL select with CONCAT condition(MySQL选择与CONCAT条件)
Capitalize first letter of each word, in existing table(将现有表格中每个单词的首字母大写)
How to retrieve SQL result column value using column name in Python?(如何在 Python 中使用列名检索 SQL 结果列值?)
Update row with data from another row in the same table(使用同一表中另一行的数据更新行)
Exporting results of a Mysql query to excel?(将 Mysql 查询的结果导出到 excel?)