0

This function compiled successfully:

CREATE OR REPLACE FUNCTION FieldValidations1(tbl_name varchar(35),col_name varchar(25), error_flag varchar(3))
RETURNS void AS $$
declare
    cust_rec RECORD;
BEGIN
    execute format($sel$

    FOR cust_rec IN SELECT %I FROM %s 
    LOOP
    RAISE NOTICE 'inside loop';
    END LOOP;

    $sel$,
    col_name,tbl_name);
END;
$$ LANGUAGE plpgsql;

But while calling the function,

select FieldValidations1('raw_tbl1','col1','gg');

the error appears like this

ERROR:  syntax error at or near "FOR"
LINE 3: FOR cust_rec IN SELECT col1 FROM raw_tbl1
    ^
QUERY:

FOR cust_rec IN SELECT col1 FROM raw_tbl1
LOOP
RAISE NOTICE 'inside loop';
END LOOP;

CONTEXT:  PL/pgSQL function "fieldvalidations1" line 6 at EXECUTE statement

Can anyone explain what's wrong?

0

2 Answers 2

2

You must be aware that plpgsql functions are only tested on a superficial syntactical level in CREATE FUNCTION. It does not find all possible errors, it does not try to evaluate functions.

Would work like this:

CREATE OR REPLACE FUNCTION field_validations2(tbl_name text
                                            , col_name text, error_flag text)
  RETURNS void AS
$func$
DECLARE
   cust_rec RECORD;
BEGIN
    FOR cust_rec IN
        EXECUTE format('SELECT %I FROM %I', col_name, tbl_name)
    LOOP
      RAISE NOTICE 'inside loop';
    END LOOP;
END
$func$ LANGUAGE plpgsql;

The proper syntax for a FOR-IN-EXECUTE statement can be found in the manual.

Also fixed a couple of other things. text instead of varchar(n) is just a friendly advice.

Sign up to request clarification or add additional context in comments.

Comments

-1

It is not possible to execute plpgsql. It must be plain SQL.

Comments

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.