0

我一直在尝试编写一个存储过程,该过程涉及用户输入他们希望存储数据的列,然后输入要存储的数据。到目前为止,这可行,但该列是硬编码的。

CREATE PROCEDURE `cnp_data`.`AddBehavior` (IN StudId INT,
                                           IN ColumnData VARCHAR(45))
BEGIN
    UPDATE `Behavior`
        SET `Lunch` = ColumnData                        
            WHERE `StudentId`=StudId;
END

但我想这样做,以便Lunch用户可以动态设置列。到目前为止,我坚持这一点:

CREATE PROCEDURE `cnp_data`.`AddBehavior` (IN StudId INT,
                                           IN ColumnName VARCHAR(45),
                                           IN ColumnData VARCHAR(45))
BEGIN
    SET @Var1=StudId;
    SET @Var2=ColumnName;
    SET @Var3=ColumnData;
    SET @sqlstm = CONCAT("UPDATE `Behavior`
                            SET `",@Var2,"` = ",@Var3,"
                               WHERE `StudentId`= ",@Var1,";");
    PREPARE stmt FROM @sqlstm;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END

但是当我尝试输入以下 CALL 语句时,这会引发错误

CALL AddBehavior(19, "AM Snack", "test");

错误代码:1054。“字段列表”中的未知列“测试”

我不明白为什么它试图将@Var3 查找为列,而不是将其设置为@Var2 列中的数据。

感谢大家的任何帮助或见解!

4

1 回答 1

0

这行得通,谢谢安东尼·麦格拉思。

CREATE PROCEDURE `cnp_data`.`AddBehavior` (IN StudId INT,
                                           IN ColumnName VARCHAR(45),
                                           IN ColumnChoice VARCHAR(45))
BEGIN
    SET @Var1=StudId;
    SET @Var2=ColumnName;
    SET @Var3=ColumnChoice;
    SET @Var4=CURRENT_DATE;
    SET @sqlstm = CONCAT("UPDATE `Behavior`
        SET `",@Var2,"` = """,@Var3,"""
            WHERE `StudentId`= ",@Var1," AND CurrentDate=""",@Var4,""";");
    PREPARE stmt FROM @sqlstm;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
于 2020-03-19T04:10:19.163 回答