0

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?

2
  • 3
    You cannot parametrize your table (or column) name. If you want to do that, you need to concatenate together your SQL statement (which always opens the risk of SQL injection) Commented Nov 13, 2013 at 9:47
  • 1
    Just change command.Parameters.AddWithValue("id", id) into sql = sql.Replace("@Id", id.ToString(CultureInfo.InvariantCulture) Commented Nov 13, 2013 at 10:02

2 Answers 2

4

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

Take a look at Dynamic SQL instead.

Sign up to request clarification or add additional context in comments.

Comments

0

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

string sql = "SELECT colName1, colName2 , colname ......FROM myTable"+id;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.