【问题标题】:MySQL - Prepared statements not returning full queryMySQL - 准备好的语句不返回完整的查询
【发布时间】:2018-11-27 17:03:16
【问题描述】:

我在存储过程中使用prepare语句。

DROP PROCEDURE
IF EXISTS test;
delimiter //
  CREATE PROCEDURE
    test(IN query varchar(100))
  begin     
        SET @query =CONCAT('select * FROM db.',query,' LIMIT  10000;');
        select @query;
        PREPARE arcive_stmt FROM @query;
        EXECUTE arcive_stmt;
   commit;
   DEALLOCATE PREPARE arcive_stmt;
 END //
delimiter ; 

此过程将从用户输入中获取表和 where 条件并运行选择查询。

所以我执行了这个:

mysql> call test ('logs where created_date < DATE(Now() - INTERVAL 3 month) and updated_at < DATE(Now() - INTERVAL 3 month');

但是我收到了这个错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT  10000' at line 1

我使用 print @query 来调试它。然后它会截断我的输入字符串。

select * FROM db.logs where created_date < DATE(Now() - INTERVAL 3 month) and updated_at < DATE(Now() - INTER LIMIT  10000;

它把我的刺截断到DATE(Now() - INTER。 有人可以帮我理解和解决这个问题吗?

【问题讨论】:

    标签: mysql sql prepared-statement


    【解决方案1】:

    您的 IN 参数长度仅设置为 100。虽然您的查询字符串输入远远超过 100 个字符长度。

    将其增加到更大的值,例如:255

    DROP PROCEDURE
    IF EXISTS test;
    delimiter //
      CREATE PROCEDURE
        test(IN query varchar(255))  -- increase to a bigger value
      begin     
            SET @query =CONCAT('select * FROM db.',query,' LIMIT  10000;');
            select @query;
            PREPARE arcive_stmt FROM @query;
            EXECUTE arcive_stmt;
       commit;
       DEALLOCATE PREPARE arcive_stmt;
     END //
    delimiter ; 
    

    另外注意:您输入的query 字符串未指定ORDER BY 子句。请注意,数据以无序方式存储。如果没有ORDER BY 子句,LIMIT.. 得到的结果将是不确定的。

    【讨论】:

      【解决方案2】:

      您声明该过程采用 100 个字符长的字符串

      CREATE PROCEDURE
        test(IN query varchar(100)) <-- ONE HUNDRED CHARS LIMIT
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-02
        • 2018-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-09
        • 1970-01-01
        • 2011-09-16
        相关资源
        最近更新 更多