Next.js Discord

Discord Forum

Vercel postgres sql - how can I embed the table name as a variable?

Unanswered
Bonga shad posted this in #help-forum
Open in Discord
Bonga shadOP
I am using Vercel's database and so their SDKs.
I have two tables to run the same queries against, depending on the input value.

so I thought I could write a query like this:

function getData(inputValue: number) {
  const tableName = number > 10  ?  'tableA' : 'tableB';
  const data = sql<MyDataDefinition>`
    SELECT *
    FROM ${tableName}
    WHERE 1=1
  `;
  return data.rows;
}


But it failed, with an error NeonDbError: syntax error at or near "$1" . If I replace the $tableName variable with one of the table names, it would run.

Anybody know how to properly pass table name as a variable? Thanks.

5 Replies

American Crow
${tableName}
Bonga shadOP
@American Crow my bad, that's what I did that didn't work. i missed that brackets in my original post, i added them.
American Crow
Okay. Gotcha i just saw the syntax error. Can't help with the actualy error, never used the vercel postgres
American Crow
I found this in the docs:
https://vercel.com/docs/storage/vercel-postgres/sdk#preventing-sql-injections

It links to this:
https://node-postgres.com/features/queries#parameterized-query

Which says PostgreSQL does not support parameters for identifiers. If you need to have dynamic database, schema, table, or column names (e.g. in DDL statements) use pg-format package which links to this:
https://www.npmjs.com/package/pg-format
Bonga shadOP
Nice, that will solve my problem. Thank you!