0

在 MySql 中,如何将函数内的选择中的值加载到函数内的变量中?

该选择仅返回一行。

桌子

"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;

4

1 回答 1

2

利用SELECT ... INTO var_list

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演示

于 2013-06-06T11:18:16.617 回答