【问题标题】:How can I send a table as a parameter to stored procedure in MySQL?如何将表作为参数发送到 MySQL 中的存储过程?
【发布时间】:2021-04-08 23:42:54
【问题描述】:

我在 MySQL 中有一个存储过程,例如:

DELIMITER $$
CREATE PROCEDURE addIns(IN insCode VARCHAR(21), IN insName VARCHAR(21), IN stat BIT(1))
BEGIN
    INSERT INTO institution(institution.institution_code, institution.institution_name, institution.is_active) 
    VALUES (insCode, insName, stat);
END$$
DELIMITER ;

但我想要这样:

DELIMITER $$
CREATE PROCEDURE addIns(IN _institution)
BEGIN
    INSERT INTO institution(institution.institution_code, institution.institution_name, institution.is_active)
    VALUES (_institution.institution_code, _institution.institution_name, _institution.is_active);
END$$
DELIMITER ;

因为我想在 Java Spring App 中使用这个存储过程。 如何提供?

我的直觉表是:

【问题讨论】:

  • 请提供样本数据和期望的结果。示例代码不清楚。另外,我的猜测是你并不真的需要这个。相反,您的数据模型有问题。
  • 我编辑了。我想在 Java Spring 中使用这个存储过程。我发送一个 post 请求作为一个 instution,而不是我想从这个存储过程保存到 db。 @GordonLinoff
  • 不能,因为对于函数或存储过程的参数,只允许here提到的数据类型,TABLE不是其中之一。
  • 您可以将表名作为参数发送给 SP。但是要将此参数值用作表名,您必须使用动态 SQL(准备语句)。 但我想要这样你必须使用INSERT .. SELECT而不是INSERT .. VALUES

标签: mysql sql stored-procedures insert


【解决方案1】:
CREATE PROCEDURE addIns(IN _institution)
BEGIN
    @sql := CONCAT( 'INSERT INTO institution (institution_code, institution_name, is_active) SELECT institution_code, institution_name, is_active FROM ' , _institution);
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DROP PREPARE stmt;
END

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 2021-10-31
    • 1970-01-01
    相关资源
    最近更新 更多