我有以下代码,它应该返回比提供的年龄参数更年轻的客户列表以及找到的记录总数。
我的表格包括:列ID,FIRST_FIRSTNAME,LASTNAME,DATE_OF_BIRTH
我可以轻松地在这个程序的语法,逻辑和格式上犯了一些错误,但请原谅我,我是新手!以下是我的sql过程:
DELIMITER $$
DROP PROCEDURE IF EXISTS sample_procedure$$
CREATE PROCEDURE sample_procedure(IN actualinput INT)
BEGIN
DECLARE no_more_customers int(4);
DECLARE l_customer_count int(4);
DECLARE l_id varchar(1);
DECLARE l_first_name varchar(10);
DECLARE l_last_name varchar(10);
DECLARE l_date_of_birth varchar(20);
DECLARE customer_list varchar(250);
DECLARE dateinput DATE;
SET dateinput=DATE_SUB(now(), interval actualinput year);
DECLARE cid CURSOR FOR
SELECT ID, FIRST_FIRSTNAME, LAST_NAME, DATE_OF_BIRTH
FROM customers WHERE DATE_OF_BIRTH >= dateinput;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_customers=1;
SET no_more_customers=0;
SET l_customer_count=0;
OPEN cid;
cid_cursor: REPEAT
FETCH cid INTO l_id, l_first_name, l_last_name, l_date_of_birth; IF no_more_customers THEN
LEAVE cid_cursor;
END IF;
SET customer_list=concat(customer_list, l_id,',',l_first_name,',',l_last_name,',',l_date_of_birth);
SET l_customer_count=1+l_customer_count;
UNTIL no_more_customers
END REPEAT cid_cursor;
CLOSE cid;
SET no_more_customers=0;
SELECT customer_list AS Customers;
SELECT concat(l_customer_count);
END;
$$
我在用于计算客户年龄的方法中似乎有错误,可能是我用来调用游标的方法的问题,我的最终客户列表只返回null。 提前谢谢......
答案 0 :(得分:3)
我可以假设应该初始化变量'customer_list',例如 -
...
DECLARE customer_list VARCHAR(250) DEFAULT '';
...
因为'SET customer_list = CONCAT(customer_list,...)'当customer_list为NULL时,也会返回NULL。
利用MySQL Stored Procedure Debugger。希望此功能对您有所帮助。