I want create a function which removes rows and returns true if there are no errors:
CREATE OR REPLACE FUNCTION s_grnplm_tt.sp_del_stts_cd(num text, package_name text, stts_cd text)
returns bool
LANGUAGE plpgsql as
$func$
BEGIN
EXECUTE
'delete FROM s_grnplm_'||num||'tt.log_copy d WHERE d.package_name =' ||package_name|| ' and d.stts_cd = $1'
using stts_cd;
return true;
end;
$func$;
I'm calling a function: select s_grnplm_tt.sp_del_stts_cd('089', '0202_20232211_2434', 'U')
but I get an error: SQL Error [42601]: ERROR: syntax error at or near "_20232211_2434"Where: PL/pgSQL function sp_del_stts_cd(text,text,text) line 3 at EXECUTE statement
First, you should to read some about SQL injection issue. You never to pass string variables to SQL just by append
||operator. You should to sanitize string values before. It can be done by usage functionformatand related placeholders or by using functionsquote_identandquote_literal.Second, when you have problem with dynamic SQL (
EXECUTE) statement, then you should to useRAISE NOTICEstatement and display executed SQL statement. Then the issue is clean:You are missing apostrophes in predicate
d.package_name =0202_20232211_2434.Your function can be rewritten to:
Now, the query is correct:
The dynamic SQL requires passing only SQL identifiers as strings. Others can be passed binary by usage
USINGclause. So predicated.package_name =should be used similarly tod.stts_cd =predicate: