I want to return 10 json strings with mysql with data from my database, but i get the fallowing error: SQL Error (1172): Result consisted of more than one row! yes i know the result consist in more rows, they are 10, the problem is how to print them all in different rows?
CREATE DEFINER=`root`@`localhost` FUNCTION `search_for`(`value` TEXT)
RETURNS text CHARSET latin1
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE sid TEXT;
DECLARE semail TEXT;
DECLARE sname TEXT;
DECLARE slastname TEXT;
DECLARE response TEXT;
SELECT id,email,name,lastname INTO sid,semail,sname,slastname
FROM user WHERE email LIKE CONCAT('%',value,'%')
OR lastname LIKE CONCAT('%',value,'%')
OR name LIKE CONCAT('%',value,'%') LIMIT 10;
IF (semail IS NOT NULL) THEN
SET response = CONCAT('{"response":1,"id":',sid,',"email":"',semail,'","name":"',sname,'","lastname":"',slastname,'"}');
ELSE
SET response = CONCAT('{"response":0}');
END IF;
RETURN response;
END
after i use cursor and loop the method to get search result in multiple rows look like this:
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE ids TEXT;
DECLARE response TEXT;
DECLARE ids_cursor CURSOR FOR
SELECT id,email,name,lastname -- INTO ids,semail,sname,slastname
FROM user WHERE email LIKE CONCAT('%',value,'%')
OR lastname LIKE CONCAT('%',value,'%')
OR name LIKE CONCAT('%',value,'%');
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 2;
OPEN ids_cursor;
get_ids: LOOP
FETCH ids_cursor INTO ids;
IF finished = 2 THEN
LEAVE get_ids;
END IF;
SET response = CONCAT(ids,";",response);
END LOOP get_ids;
CLOSE ids_cursor;
RETURN response;
END
and i still get a little error (1328): Incorrect number of FETCH variables! why?
Update
edited next line:
SELECT id --,email,name,lastname -- INTO ids,semail,sname,slastname
get a NULL
response
Must not use function. Maybe define view from this query ? Like this:
create or replace view userquery select if(semail is not null, CONCAT('{"response":1,"id":',sid,',"email":"',semail,'","name":"',sname,'","lastname":"',slastname,'"}'),"0") response, email,lastname,name FROM user ;
And query
select response from userquery where ...
Or simply use "if" in query, without function.
Yes, in the end i will not use loop and cursor to reg response from this query, i will use a json string like this:
BEGIN
DECLARE response TEXT;
SELECT CONCAT('{',GROUP_CONCAT(id SEPARATOR ','),'}') INTO response
FROM user
WHERE email LIKE CONCAT('%',value,'%')
OR lastname LIKE CONCAT('%',value,'%')
OR name LIKE CONCAT('%',value,'%');
IF( response IS NOT NULL ) THEN
RETURN response;
ELSE
RETURN CONCAT('{"response":0}');
END IF;
END
i think sql cursor and loop's are for more advanced results, anyway work just finelike i did here, tcx!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.