Question

I have database tables that dynamically gets created. They all have the same name but with a unique ID at the end of the name like for example myTable1, myTable2 and so on.

I have these IDs but the question is how should my SQL look like in C# using sqlclient?

For example:

string sql = "SELECT * FROM myTable"+id;

Works but is still open for SQL injections

I've also tried:

string sql = "SELECT * FROM myTable@id";
command.Parameters.AddWithValue("id", id);

But does not work since the sql reads the table name as myTable@id not for example myTable1

Is there a way to insert parameters for the table name?

Was it helpful?

Solution

Regular SQL can't have parameters on field names or table names, just on values.

Take a look at Dynamic SQL instead.

OTHER TIPS

I think using column names in this particular query may do the job .

string sql = "SELECT colName1, colName2 , colname ......FROM myTable"+id;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top