1

I'm writing an embedded SQL application in C language. The application receives a string from a function and I need to create a table whose name is taken from that string. I have to create several tables with different names, but I don't know the number and the name of the tables from the start.

This is what i want to do:

tablename = function();
...
EXEC SQL CREATE TABLE :tablename ( ... );

But I got this error:

ERROR: syntax error at or near ":tablename"
2
  • what is exactly EXEC SQL CREATE TABLE : in c? Commented Apr 30, 2015 at 7:53
  • 2
    First create a string containing a piece of SQL and then execute this piece of SQL. Beware of SQL injection, you might loose everything.... Check the quote_ident() function in PostgreSQL. Commented Apr 30, 2015 at 7:55

1 Answer 1

2

If you have to create the same data structures but with unique names then create procedure that creates such table:

CREATE OR REPLACE FUNCTION create_temp_table(table_name varchar)
  RETURNS void AS
$BODY$
BEGIN
    EXECUTE 'CREATE TABLE ' ||  quote_ident(table_name) || ' (id SERIAL, kn VARCHAR, kv VARCHAR)';
END;
$BODY$
LANGUAGE plpgsql;

You can call it from SQL via:

SELECT create_temp_table('tmp_table_31');

(notice use of quote_ident() to prevent SQL Injection)

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

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.