Home > Database > Mysql Tutorial > How Can I Pass String Arrays to MySQL Stored Procedures?

How Can I Pass String Arrays to MySQL Stored Procedures?

Susan Sarandon
Release: 2024-12-05 02:44:10
Original
313 people have browsed it

How Can I Pass String Arrays to MySQL Stored Procedures?

Passing Array Parameters to MySQL Stored Routines

When working with variable-length arrays of strings, passing them as parameters to MySQL stored routines can pose a challenge. To overcome this, an alternative solution is to concatenate the array values into a single string and utilize prepared statements.

The following code snippet outlines the process:

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 ;
Copy after login

To use this stored procedure, you can initialize a string variable with the array values separated by commas and call the procedure, passing the variable as an argument:

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

This solution effectively allows you to pass an array of string values to a MySQL stored routine and work with the data in an in-memory table.

The above is the detailed content of How Can I Pass String Arrays to MySQL Stored Procedures?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template