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.
CodePudding user response:
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.
