skip to Main Content

enter image description here

What is causing the error here? If I’m not confusing anything, everything is done as it should

CREATE FUNCTION convert_temperature(temperature real, current_scale varchar DEFAULT 'Fahrenheit') RETURNS real AS $$
BEGIN
    IF(current_scale = 'Celsius')
        THEN RETURN temperatue*1.8+32
    ELSE
        RETURN (temperature-32)/1.8
    END IF;
END
$$ LANGUAGE plpgsql

Gives a message:

ERROR: syntax error (example position: "RETURN")

I asked chatGPT where there could be a mistake, to which he answered me:
"There is no error in this function."

2

Answers


  1. No need for pl/pgsql, SQL is good enough and faster. You can also use immutable because the function has no dependencies on any table.

    CREATE FUNCTION convert_temperature(temperature real, current_scale varchar DEFAULT 'Fahrenheit')
        RETURNS real
        LANGUAGE sql
        IMMUTABLE
    AS
    $$
        SELECT  CASE
            WHEN current_scale = 'Celsius'
                THEN $1*1.8+32
            ELSE ($1-32)/1.8
        END;
    $$;
    
    SELECT convert_temperature(25);
    SELECT convert_temperature(25, 'Fahrenheit');
    SELECT convert_temperature(25, 'Celsius');
    SELECT convert_temperature(25, 'Kelvin'); -- fail
    
    Login or Signup to reply.
  2. When asked correctly at ChatGTP it answers:

    I can see the issue in your code. There is a small typo in the RETURN statement for the Celsius conversion. You have misspelled the variable name temperature as temperatue. Here’s the corrected version of your code:

    CREATE FUNCTION convert_temperature(temperature real, current_scale varchar DEFAULT 'Fahrenheit') RETURNS real AS $$
    BEGIN
        IF current_scale = 'Celsius'
        THEN
            RETURN temperature * 1.8 + 32;
        ELSE
            RETURN (temperature - 32) / 1.8;
        END IF;
    END;
    $$ LANGUAGE plpgsql;
    

    The main changes made are:

    Corrected temperatue to temperature in both RETURN statements.

    Removed unnecessary parentheses around the IF condition.

    Added semicolons at the end of each RETURN statement.
    With these corrections, your function should work as intended without syntax errors.

    Conclusion: Do not value ChatGPT as the source of anything (good or bad) when you ask the wrong question, you will not get a correct answer!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search