Ошибка 1415 mysql

I am not trying to return a result set and I have no idea what I’m doing wrong here.
MySQL 5.5

delimiter $$

CREATE FUNCTION CheckAccount(
    i_username varchar(50)
) RETURNS integer

BEGIN

    DECLARE v_validUserId int;
    DECLARE v_validMembership int;
    DECLARE o_Status integer;

    SELECT vvalidUserId = u.UserId
    FROM Users u
    WHERE u.Username = i_username;

    IF( v_validUserId IS NULL ) THEN
        SET o_Status = 2; -- Invalid username
    ELSE
        SET o_Status = 1; -- Good
    END IF;


    IF(o_Status != 2 ) THEN
            SELECT v_validMembership = 1
            FROM Users u
            JOIN UserMemberships um on um.UserId = u.userId
            JOIN Memberships m on m.MembershipId = um.MembershipId
            WHERE um.MembershipExpireDateTime > CURDATE()
            AND u.UserId = v_validUserId;

            IF( v_validMembership IS NULL ) THEN 
                SET o_Status = 3; -- Invalid membership
            END IF;
    END IF;

    RETURN o_status;

END $$
DELIMITER ;

Any help will be greatly appreciated!

Trinimon's user avatar

Trinimon

13.8k9 gold badges44 silver badges60 bronze badges

asked Apr 23, 2013 at 19:06

sqltracy's user avatar

I’m not sure if you can assign variables that way, try use INTO statement for your selects. For example:

SELECT 
    u.UserId INTO vvalidUserId 
FROM 
    Users u
WHERE 
    u.Username = i_username;

answered Apr 24, 2013 at 1:48

b.b3rn4rd's user avatar

b.b3rn4rdb.b3rn4rd

8,4242 gold badges44 silver badges55 bronze badges

1

The error message in this case tells the most important part:

Not allowed to return a result set from a function

This behaviour is consistent with what’s documented in MySQL manual on stored procedures and functions:

For statements that can be determined at function definition time to return a result set, a Not allowed to return a result set from a function error occurs (ER_SP_NO_RETSET).

You assign values to your @Pn variables using select statements that return a resultset and this is not allowed in a function. You have to remove these statements from your code. RETURN river returns a result value, but not a result set.

I’m also worried that you use session variables (variables defined as @variable_name) which are shared across a connection, so potentially multiple call to the same function at the same time within a connection may interfere with each other.

A stored function is only supposed to return a single value as its output in with the return statement. Anything else is considered as a side effect. If you want your MySQL script to populate multiple variables, then you must use a stored procedure, you cannot use a stored function.

Issue

Trying to create a conditional-based function that will return a result. I don’t if it’s the way I am setting the result value that is causing the error? Making MySQL throw the error code 1415 Not allowed to return a result set from a function.

DELIMITER $$

CREATE FUNCTION GetTechFull ( table_flag INT,person_pk CHAR(11) )
RETURNS INT

BEGIN

    DECLARE firstName VARCHAR(64);
    DECLARE lastName VARCHAR(64);
    DECLARE outputRes VARCHAR(64) DEFAULT NULL;

    IF table_flag IS NULL OR person_pk IS NULL THEN
        RETURN NULL;
    END IF;
    IF table_flag = 1 THEN
        SELECT CONCAT(LEFT(ResFirstName,1), " ", ResLastName) as name,ResPhone as telephone, TPGText as pay_grade FROM cpts451_secretproject_rds.ww_techfull;
        SET outputRes =  CONCAT(LEFT(firstName,1), " ", lastName);
    END IF;
    IF table_flag = 0 THEN
        SELECT stdFirstName,stdLastName INTO firstName,lastName FROM student WHERE student.stdNo = person_pk;
        SET outputRes =  CONCAT(LEFT(firstName,1), " ", lastName);
    END IF;
    RETURN outputRes;
END$$

DELIMITER ;

Solution

your code has multiple problems, but the bggest ist that you a using a «normal select, which would return a result set, which is not allowed.

so oyu can only use, SELECT .. INTO..FROM..WHERE to get rid of the error message.

Iyour return Value doesn’t correspond with the variable ‘outputResthey must be f the same datatype

MySQL 8 also wants a DETERMINIsTIC added

Below you see a working code sample, so that you can go from here, to whereever you want

CREATE tABLE student(stdNo int, stdFirstName VARCHAR(64), stdLastName VARCHAR(64))
INSERT INTO student VALUES(1,'test2','testlast')
CREATE TABLe ww_techfull(ResNo int, ResFirstName VARCHAR(64), ResLastName VARCHAR(64)
,ResPhone varchar(16),TPGText varchar(64))
INSERT INTO  ww_techfull VALUES(1,'testfrist', 'Testlast','012345656778','Bad')
CREATE FUNCTION GetTechFull ( table_flag INT,person_pk CHAR(11) )
RETURNS CHAR(64) DETERMINISTIC

BEGIN

    DECLARE firstName CHAR(64);
    DECLARE lastName CHAR(64);
    DECLARE telephone CHAR(64);
    DECLARE pay_grade CHAR(64);
    DECLARE outputRes CHAR(64) DEFAULT NULL;

    IF table_flag IS NULL OR person_pk IS NULL THEN
        RETURN NULL;
    END IF;
    IF table_flag = 1 THEN
        SELECT LEFT(CONCAT(LEFT(ResFirstName,1), " ", ResLastName),64) 
        ,ResPhone  , TPGText 
        INTO outputRes
        ,telephone,  pay_grade 
        FROM ww_techfull WHERE ResNo = person_pk;
        SET outputRes =  LEFT(outputRes,64);
    END IF;
    IF table_flag = 0 THEN
        SELECT LEFT(CONCAT(LEFT(stdFirstName,1), " ",stdLastName),64) INTO outputRes 
        FROM student WHERE student.stdNo   = person_pk;
        SET outputRes =  LEFT(outputRes,64);
    END IF;
    RETURN outputRes;
END
SELECT GetTechFull(0,1)
| GetTechFull(0,1) |
| :--------------- |
| t testlast       |
SELECT GetTechFull(1,1)
| GetTechFull(1,1) |
| :--------------- |
| t Testlast       |

db<>fiddle here

Answered By – nbk

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

QUESTION: Error 1415, not allowed to return a result set from function

I can’t seem to find my problem here, I don’t think I’m doing anything complicated.

DELIMITER //
CREATE FUNCTION test_glaccounts_description
(
   account_description_param CHAR(100)
)
RETURNS INT
BEGIN
  
  DECLARE description_exists INT;
   
  DECLARE CONTINUE HANDLER FOR NOT FOUND
	SET description_exists = FALSE;
  
  SET description_exists = TRUE;
  
  SELECT account_description
  FROM general_ledger_accounts
  WHERE account_description = account_description_param;
  
  RETURN description_exists;
END//

DELIMITER ;

Я подозреваю, что вы не можете вернуть набор результатов из функции. В функции вам нужно объявить переменную и заполнить ее

Select count(idFriendship) INTO @1
from friendship
Where users.iduser=friendship.iduser1;

return @1;

, вы должны иметь возможность использовать функцию в некотором SQL, поэтому разрешено возвращать только одно значение

https: //dev.mysql.com/doc/refman/8.0/en/create-function-udf.html

ответ дан T.S. 17 January 2019 в 02:25

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка 143 вольво икс си 90
  • Ошибка 1429 исключение ole idispatch код 0
  • Ошибка 1426 приора 16 клапанов
  • Ошибка 1426 пассат б5

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии