Search code examples
c#wpfnpgsql

Npgsql to create tables


I'm struggling to create a table using Npgsql.

using (NpgsqlCommand command = new NpgsqlCommand("CREATE TABLE @tableName(asdf TEXT)", con))
{
    command.Parameters.Add(new NpgsqlParameter("@tableName", "test"));
    command.ExecuteReader();
}

throws an exception:

Npgsql.PostgresException: '42601: syntax error at or near "$1"', which doesn't bring any clue to find out what is wrong.

How can I create a table using parameters? Is it actually possible?


Solution

  • Table names cannot be parameterized - you must integrate the name in your DDL string; parameterization is (among other things) about generating and reusing a single query plan regardless of the parameter's content, but that doesn't apply to CREATE TABLE statements.

    If you need to create tables dynamically, you can use string interpolation, but be sure to escape properly to avoid SQL injection for user inputs.