这个mysql函数有什么问题?

时间:2017-06-04 09:03:32

标签: mysql

当我运行此功能时

CREATE PROCEDURE alege()
    BEGIN
        declare v_prenumeNou VARCHAR(15);
        declare v_numeRandom INTEGER(10);
        declare v_prenumeRandom INTEGER(10);
        declare v_idCutremurRandom INTEGER(10);

        set v_numeRandom = 1 + CEIL ( RAND() * 50 );
        set v_prenumeRandom = 1 + CEIL ( RAND() * 50 );
        set v_idCutremurRandom = 1 + CEIL ( RAND() * 50 );

        select prenume into v_prenumeNou from (SELECT prenume, rownum as v_rn from voluntari) where v_rn=v_prenumeRandom;
        select nume into v_numeNou from (SELECT nume, rownum as v_rn from voluntari) where v_rn=v_numeRandom;

        v_idPersoanaNou := v_idPersoanaNou + 1;

        INSERT INTO voluntari (IDCUTREMUR, IDPERSOANA, NUME, PRENUME) 
        VALUES (CONCAT('C',IFNULL(v_idCutremurRandom, '')), CONCAT('V',IFNULL(v_idPersoanaNou, '')) , v_numeNou, v_prenumeNou);
END;

我有这个错误

  

[Err] 1248 - 每个派生表必须有自己的别名

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您必须在select into语句中为每个子查询添加别名:

select prenume 
into v_prenumeNou 
from (SELECT prenume, rownum as v_rn 
      from voluntari) t1  <-----------
where v_rn=v_prenumeRandom;

select nume 
into v_numeNou 
from (SELECT nume, rownum as v_rn 
      from voluntari) t1 <------------
where v_rn=v_numeRandom;

答案 1 :(得分:0)

试试这个,只需更改from子句的别名(每个派生表必须有一个别名):

CREATE PROCEDURE alege()
    BEGIN
        declare v_prenumeNou VARCHAR(15);
        declare v_numeRandom INTEGER(10);
        declare v_prenumeRandom INTEGER(10);
        declare v_idCutremurRandom INTEGER(10);

        set v_numeRandom = 1 + CEIL ( RAND() * 50 );
        set v_prenumeRandom = 1 + CEIL ( RAND() * 50 );
        set v_idCutremurRandom = 1 + CEIL ( RAND() * 50 );

        select prenume into v_prenumeNou from (SELECT prenume, rownum as v_rn from voluntari) AS A where v_rn=v_prenumeRandom;
        select nume into v_numeNou from (SELECT nume, rownum as v_rn from voluntari) AS B where v_rn=v_numeRandom;

        v_idPersoanaNou := v_idPersoanaNou + 1;

        INSERT INTO voluntari (IDCUTREMUR, IDPERSOANA, NUME, PRENUME) 
        VALUES (CONCAT('C',IFNULL(v_idCutremurRandom, '')), CONCAT('V',IFNULL(v_idPersoanaNou, '')) , v_numeNou, v_prenumeNou);
END;