Why cannot I use bind variables in DDL/SCL statements in dynamic SQL?

Bind variables are not allowed in DDL statements. So following statements will cause errors: Example #1: DDL statement. Will cause ORA-01027: bind variables not allowed for data definition operations EXECUTE IMMEDIATE ‘CREATE TABLE dummy_table ( dummy_column NUMBER DEFAULT :def_val )’ USING 42; Example #2: DDL statement. Will cause ORA-00904: : invalid identifier EXECUTE IMMEDIATE ‘CREATE … Read more

Error when setting n_distinct using a plpgsql variable

This is by design. The manual explains in the chapter Variable Substitution: Variable substitution currently works only in SELECT, INSERT, UPDATE, and DELETE commands, because the main SQL engine allows query parameters only in these commands. To use a non-constant name or value in other statement types (generically called utility statements), you must construct the … Read more

Return SETOF rows from PostgreSQL function

Sanitize function What you currently have can be simplified / sanitized to: CREATE OR REPLACE FUNCTION func_a (username text=””, databaseobject text=””) RETURNS ???? LANGUAGE plpgsql AS $func$ BEGIN RETURN QUERY EXECUTE format (‘SELECT * FROM %s v1 LEFT JOIN %I v2 USING (id)’ , CASE WHEN username=”*” THEN ‘view1’ ELSE ‘view3’ END , databaseobject); END … Read more

Ad hoc queries vs stored procedures vs Dynamic SQL [closed]

Stored Procedures Pro: Good for short, simple queries (aka OLTP–i.e. add, update, delete, view records) Pro: Keeps database logic separate from business logic Pro: Easy to troubleshoot Pro: Easy to maintain Pro: Less bits transferred over network (i.e. only the proc name and params) Pro: Compiled in database Pro: Better security (users don’t need direct … Read more

DROP FUNCTION without knowing the number/type of parameters?

Basic query This query creates all necessary DDL statements: SELECT ‘DROP FUNCTION ‘ || oid::regprocedure FROM pg_proc WHERE proname=”my_function_name” — name without schema-qualification AND pg_function_is_visible(oid); — restrict to current search_path Output: DROP FUNCTION my_function_name(string text, form text, maxlen integer); DROP FUNCTION my_function_name(string text, form text); DROP FUNCTION my_function_name(string text); Execute the commands after checking plausibility. … Read more