您好,我很乐意尝试在MySQL中正确解析存储过程。
我的问题是约会。我试图让商店程序创建一个开始日期,即当月的开始日期,例如2009-07-01。使用这个日期我然后使用DATA_ADD()函数添加一个月,使其显示为2009-08-01。
但是我的问题是,当我尝试运行procdure来创建它时,我收到以下错误:
Script line: 7 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 'DECLARE
cur_month INT;
SET cur_month = (SELECT MONTH(CURRENT_DATE()));
商店程序的代码如下所示:
DROP PROCEDURE IF EXISTS sp_test;
DELIMITER //
CREATE PROCEDURE sp_test()
BEGIN
/*we work out the start and end dates*/
DECLARE cur_year INT;
SET cur_year = (SELECT YEAR(CURRENT_DATE()));
DECLARE cur_month INT;
SET cur_month = (SELECT MONTH(CURRENT_DATE()));
DECLARE temp_date VARCHAR(10);
SET temp_date = (SELECT CONCAT(cur_year,'-',cur_month,'-01'));
DECLARE start_date DATE;
SET start_date = (SELECT CAST(temp_date AS DATE)));
DECLARE end_date DATE;
SET end_date = (SELECT DATE_ADD(start_date, INTERVAL 1 MONTH));
INSERT INTO my_table (startdate, enddate)VALUES(start_date, end_date);
END; //
DELIMITER ;
我独立运行查询并且它们都返回正确的值并正常工作,当我将它们添加到存储过程时,它只会因语法错误而失败。
我在这里错过了什么导致我的头疼?
...谢谢
答案 0 :(得分:2)
您需要在BEGIN - END块的开头DECLARE所有变量。您的CAST行中也有不匹配的括号(额外收盘价)。以下应该有效:
DROP PROCEDURE IF EXISTS sp_test;
DELIMITER //
CREATE PROCEDURE sp_test()
BEGIN
/*we work out the start and end dates*/
DECLARE cur_year INT;
DECLARE cur_month INT;
DECLARE temp_date VARCHAR(10);
DECLARE start_date DATE;
DECLARE end_date DATE;
SET cur_year = (SELECT YEAR(CURRENT_DATE()));
SET cur_month = (SELECT MONTH(CURRENT_DATE()));
SET temp_date = (SELECT CONCAT(cur_year,'-',cur_month,'-01'));
SET start_date = (SELECT CAST(temp_date AS DATE));
SET end_date = (SELECT DATE_ADD(start_date, INTERVAL 1 MONTH));
INSERT INTO my_table (startdate, enddate)VALUES(start_date, end_date);
END; //
DELIMITER ;
答案 1 :(得分:0)
我已经尝试过你的例子,它适用于我的MySQL 5.0.32:
delimiter //
CREATE PROCEDURE sp_test()
BEGIN
DECLARE cur_year INT;
SET cur_year = (SELECT YEAR(CURRENT_DATE()));
INSERT INTO tt (y) VALUES (cur_year);
END; //
delimiter ;
CREATE TABLE tt (y INT);
CALL sp_test();
Query OK, 1 row affected (0.00 sec)
您可以尝试将SET重写为
SELECT YEAR(CURRENT_DATE()) INTO cur_year;
会起作用吗?你的MySQL版本是什么?..
答案 2 :(得分:0)
在开始为它们赋值之前,你必须声明所有变量,以下代码似乎对我有用:
`DELIMITER $$
DROP PROCEDURE IF EXISTS test.sp_test $$ CREATE PROCEDURE test.sp_test() BEGIN
/ 我们计算出开始和结束日期 / DECLARE cur_year INT; DECLARE cur_month INT; DECLARE temp_date VARCHAR(10); DECLARE start_date DATE; DECLARE end_date DATE;
SET cur_year =(SELECT YEAR(CURRENT_DATE()));
SET cur_month =(SELECT MONTH(CURRENT_DATE()));
SET temp_date =(SELECT CONCAT(cur_year,' - ',cur_month,' - 01'));
SET start_date =(SELECT CAST(temp_date AS DATE));
SET end_date =(SELECT DATE_ADD(start_date,INTERVAL 1 MONTH));
INSERT INTO alex.my_table(startdate,enddate)VALUES(start_date,end_date);
END $$
DELIMITER;`