snippetsqlModerate
Postgres plpgsql - Using a variable inside of a dynamic create statement
Viewed 0 times
postgrescreatestatementusingplpgsqldynamicvariableinside
Problem
Using Postgres pl/pgsql, I'm attempting to create a table using a dynamic EXECUTE command, such as:
However, I continue to receive the error message
ERROR: syntax error at or near "$1"
If I don't use the
Is there a limitation on using dynamic statements for CREATE calls?
...
DECLARE
tblVar varchar := "myTable";
BEGIN
EXECUTE 'CREATE TABLE $1 (
foo integer NOT NULL,
bar varchar NOT NULL)'
USING _tblVar;
...However, I continue to receive the error message
ERROR: syntax error at or near "$1"
If I don't use the
$1 token and, instead, write the string myTable it works just fine.Is there a limitation on using dynamic statements for CREATE calls?
Solution
In addition to what @filiprem wrote, this is how you do it properly:
Use
I also replaced the double-quotes you had around the string value in your example with single-quotes.
See:
...
DECLARE
tbl_var text := 'myTable'; -- I would not use mixed case names ..
BEGIN
EXECUTE '
CREATE TABLE ' || quote_ident(tbl_var) || '(
foo integer NOT NULL,
, bar text NOT NULL)';
...Use
quote_ident() (or format()) to defend against SQL injection and syntax errors. It double-quotes identifiers with non-standard characters or reserved words.I also replaced the double-quotes you had around the string value in your example with single-quotes.
See:
- SQL injection in Postgres functions vs prepared queries
- Insert text with single quotes in PostgreSQL
Code Snippets
...
DECLARE
tbl_var text := 'myTable'; -- I would not use mixed case names ..
BEGIN
EXECUTE '
CREATE TABLE ' || quote_ident(tbl_var) || '(
foo integer NOT NULL,
, bar text NOT NULL)';
...Context
StackExchange Database Administrators Q#5454, answer score: 13
Revisions (0)
No revisions yet.