CREATE TABLE ZAMOWIENIA( id_zamowienia INT PRIMARY KEY NOT NULL, id_uzytkownika INT, kwota_zamowienia DECIMAL(10,2)); INSERT INTO ZAMOWIENIA VALUES (1,1,20), (2,4 ,5), (3,3,100), (4,1,300), (5,2,80), (6, 1,150); SELECT * FROM ZAMOWIENIA; select count(id_uzytkownika) from ZAMOWIENIA WHERE id_uzytkownika=1; DROP FUNCTION AccountType; DELIMITER // CREATE FUNCTION AccountType( in_id_uzytkownika INT) RETURNS VARCHAR(20) DETERMINISTIC BEGIN DECLARE account_type VARCHAR(20); DECLARE in_id_uzytkownika INT; DECLARE zamowienia INT; select count(id_uzytkownika) AS zamowienia from ZAMOWIENIA WHERE id_uzytkownika=in_id_uzytkownika; select zamowienia from zamowienia; IF zamowienia >10 THEN SET account_type = 'BRONZE'; END IF; IF zamowienia >30 THEN SET account_type = 'SILVER'; END IF; IF zamowienia >60 THEN SET account_type = 'GOLD'; END IF; return account_type; END // DELIMITER ;
Advertisement
Answer
If you want to set a variable to the result of a SELECT
query, you need to use SELECT ... INTO variable
, not SELECT ... AS variable
. Your function is trying to return the result of the SELECT
query because it doesn’t store the result into a variable.
Or you can use SET
statement, which is simpler when you’re just setting a single variable.
So replace the two SELECT
statements with:
SET zamowienia = (SELECT COUNT(*) FROM from ZAMOWIENIA WHERE id_uzytkownika=in_id_uzytkownika);
Also, you shouldn’t have DECLARE
statements for the function parameters. Remove the line
DECLARE in_id_uzytkownika INT;