0

I created a postgres sql function which perform truncate and then insert rows into table. Below is the function

CREATE OR REPLACE FUNCTION reset_Default()        
RETURNS VOID AS '
BEGIN
        TRUNCATE TABLE details;
        INSERT INTO details values('car',2);
       INSERT INTO details values('bus',4);


        RETURN;
END;    
' LANGUAGE 'plpgsql';

But im getting below errors

ERROR: syntax error at or near "car" LINE 6:VALUES('car',2 ^ CREATE FUNCTION

ERROR: cannot change return type of existing function

HINT: Use DROP FUNCTION first.

Can I know the reason?

0

2 Answers 2

1

Why are you single quoting the body of your function. While this might work it can cause issues like you are experiencing. As wildplasser states use dollar signs. Then your function will compile fine.

eg

CREATE OR REPLACE FUNCTION reset_Default()        
RETURNS VOID AS $$
BEGIN
    TRUNCATE TABLE details;
    INSERT INTO details values('car',2);
   INSERT INTO details values('bus',4);
RETURN;
END;    
$$ LANGUAGE plpgsql;
Sign up to request clarification or add additional context in comments.

2 Comments

once function is created, can we run a scheduler in postgre that execute the reset_Default() periodically?
checkout pg_cron
0

You need to double up single quotes in a string. So:

CREATE OR REPLACE FUNCTION reset_Default()        
RETURNS VOID AS '
BEGIN
    TRUNCATE TABLE details;
    INSERT INTO details(col1, col2) values(''car'',2);  -- use actual column names
    INSERT INTO details(col1, col2) values(''bus'',4);

    RETURN;
END;    
' LANGUAGE 'plpgsql'

1 Comment

Or use dollar-quoting for the function body.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.