Skip to content
Advertisement

How do I get rid of this SQL error from the end of my query when inserting within a procedure?

Not sure if this is even possible but im getting a weird error at the end of my query. Any idea why?

Here is the code:

CREATE OR REPLACE PROCEDURE NewUser (g_name VARCHAR, f_name VARCHAR, u_password VARCHAR, u_email VARCHAR, u_dob DATE, p_name VARCHAR, team_id INT)
LANGUAGE plpgsql
AS $$
DECLARE s_user_id INT;
DECLARE p_user_id INT;
BEGIN
IF p_name = NULL AND team_id = NULL THEN 
    s_user_id = (SELECT MAX(user_id) FROM spectator) + 1;
    INSERT INTO spectator (user_id, given_name, family_name, password, email, date_of_birth)
    VALUES (s_user_id, g_name, f_name, u_password, u_email, u_dob);
ELSE 
    p_user_id = (SELECT MAX(user_id) FROM player) + 1;
    INSERT INTO player (user_id, given_name, family_name, password, email, date_of_birth, player_name, team_id)
    VALUES (p_user_id, g_name, f_name, u_password, u_email, u_dob, u_name, team_id);
END;
$$;

ERROR: syntax error at or near “;” LINE 15: END; ^ SQL state: 42601 Character: 727

Advertisement

Answer

You need to terminate the IF statement with END IF;. Also to check a variable against NULL, you need IS NULL rather than = NULL.

CREATE OR REPLACE PROCEDURE NewUser (g_name VARCHAR, f_name VARCHAR, u_password VARCHAR, u_email VARCHAR, u_dob DATE, p_name VARCHAR, team_id INT)
LANGUAGE plpgsql
AS $$
DECLARE s_user_id INT;
DECLARE p_user_id INT;
BEGIN
    IF p_name IS NULL AND team_id IS NULL THEN 
        s_user_id = (SELECT MAX(user_id) FROM spectator) + 1;
        INSERT INTO spectator (user_id, given_name, family_name, password, email, date_of_birth)
        VALUES (s_user_id, g_name, f_name, u_password, u_email, u_dob);
    ELSE 
        p_user_id = (SELECT MAX(user_id) FROM player) + 1;
        INSERT INTO player (user_id, given_name, family_name, password, email, date_of_birth, player_name, team_id)
        VALUES (p_user_id, g_name, f_name, u_password, u_email, u_dob, u_name, team_id);
    END IF;   --> here
END;
$$;

This types of errors are easier to spot if you properly indent the code.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement