Version: PG-13.3 with pgAdmin4
How do I escape single quotes in dynamic SQL in a function?
Here is my code
DO $$
DECLARE
uuid text;
BEGIN
uuid := 'X-2132135671';
-- Create a function using above id
EXECUTE format(E'CREATE FUNCTION system_uid() RETURNS text AS \'SELECT %L\' LANGUAGE SQL IMMUTABLE;', uuid);
END;
$$ LANGUAGE plpgsql;
here when I try to execute the code I am getting error as below
ERROR: syntax error at or near "X"
LINE 1: ...UNCTION system_uid() RETURNS text AS 'SELECT 'X-21321356...
^
QUERY: CREATE FUNCTION system_uid() RETURNS text AS 'SELECT 'X-2132135671'' LANGUAGE SQL IMMUTABLE;
CONTEXT: PL/pgSQL function inline_code_block line 7 at EXECUTE
SQL state: 42601
Please suggest correct way of doing this.