-1

I have a database with tables that are similar in name and want to access their data based on a parameter. The SQL string I am trying to use looks like this:

string sql = "SELECT * FROM @table WHERE EntryID = @ID"

and then have the parameter add the table name as such

cmd.Parameters.Add("@table", DbType.String).Value = tableName;

this is just pseudo for my actual code but this is a very close representation of what I am using.

  • 1
    Please see: [How can I Pass a Table Name to SqlCommand?](https://stackoverflow.com/questions/23357481/how-can-i-pass-a-table-name-to-sqlcommand) – Ňɏssa Pøngjǣrdenlarp Feb 09 '22 at 19:31
  • 1
    no, table names are one of the few places you can't use parameters; use a whitelist instead if your software design absolutely relies on this method and _is impossible to refactor_ – Franz Gleichmann Feb 09 '22 at 19:33
  • I figured out a work around using switch and a function to execute the code based on the case values. – Joshua Morgan Feb 09 '22 at 19:56

1 Answers1

0

You can, since you control the content of the string.

You can construct the string by adding the table name within.

Example: string sql = $"SELECT * FROM {tableName} WHERE EntryID = @ID"

This is called string interpolation. I use a similar approach in my Base Classes for CRUD operations.

Edit:

There is mention that is is open to SQL injection. If the parameter named tableName in OP's example, is controlled by the developer and does not take user input, this is safe. If for some very odd reason the parameter takes user input, this can be open to SQL injection and should NOT be done.

Marius
  • 1,420
  • 1
  • 11
  • 19
  • 1
    That can open up sql injection attacks. In MS SQL Server I would use QUOTENAME to mitigate this, not sure if SQLite has anything like that. – Crowcoder Feb 09 '22 at 20:45
  • @Marius: That is not a "parameter". "Parameter" has a very specific meaning in the context of SQL. – Ben Voigt Feb 09 '22 at 20:54
  • I know what a parameter is. And he is not trying to use one. There should also be no user input to the `tableName` parameter, so SQL injection isn't possible. He is clearly controlling which table is used, not the user, and not with user based input. – Marius Feb 09 '22 at 20:55