在MySql中,如何将函数内部的select中的值加载到函数内的变量中?
该选择只返回一行。
表格
"id" "type" "parent" "userName" "userId" "country"
"5" "1" "1" "norman" "1" "US"
"6" "2" "5" "norman" "1" "US"
"7" "3" "6" "norman" "1" "US"
"8" "10" "7" "norman" "1" "US"
"9" "1" "1" "james" "2" "UK"
功能
CREATE DEFINER=`root`@`localhost` FUNCTION `mainLinks`(`id` INT)
RETURNS varchar(1500)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
//Something like this:
DECLARE i INT(10);
SET i = id;
select id, type, parent, userName, userId, country from myTable where id=i;
//Load values from the above select into variables that can be used all over the function. Here's where I'm stuck.
SET nId = id;
SET nType = type;
//etc
//I'll then use concat to display the output.
return (select concat(nId,' ~ ',nType));
It's a lot more complicated than this and needs to go this way. I've kept it this way for this question.
END
我以这种方式调用函数SELECT id, mainLinks(id) from mytable;
答案 0 :(得分:2)
DELIMITER $$
CREATE FUNCTION mainLinks(nid INT)
RETURNS varchar(1500)
BEGIN
DECLARE aid INT;
DECLARE atype INT;
DECLARE aparent INT;
DECLARE ausername VARCHAR(32);
DECLARE auserid INT;
DECLARE aCOUNTRY VARCHAR(2);
SELECT id, type, parent, userName, userId, country
INTO aid, atype, aparent, auserName, auserId, acountry
FROM Table1
WHERE id = nid;
RETURN CONCAT(aid, atype, aparent, auserName, auserId, acountry);
END$$
DELIMITER ;
使用:
SELECT mainLinks(5);
输出:
| LINK |
----------------
| 511norman1US |
这是 SQLFiddle 演示