0

I want to create a dynamic table in which the name of the table and the names of the table columns are received from the input of the text box and then the table is created in the database.

String sql = "CREATE TABLE @TableName (@id INTEGER, @Name VARCHAR(50))";

cmd.parameters.AddWithValue("@id", textbox1.text);
cmd.parameters.AddWithValue("@Name", textbox2.text);
cmd.parameters.AddWithValue("@TableName", textbox3.text);
```
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sina
  • 11
  • 2
  • 4
    Parameters cannot be used to express table and/or column names. You need to use the old string concatenation approach or dynamic sql. – Steve Aug 24 '22 at 12:31
  • 1
    For dynamic sql see this one https://stackoverflow.com/questions/19227748/creating-a-table-using-dynamic-sql – Steve Aug 24 '22 at 12:33
  • 2
    You should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and stop using `.AddWithValue()` - it can lead to unexpected and surprising results... – marc_s Aug 24 '22 at 12:38
  • This sounds like an [XY Problem](https://xyproblem.info/) to me. Allowing the end user to create a table like this screams of a design that went the wrong way. – Sean Lange Aug 24 '22 at 13:50

1 Answers1

0

I think it`d be best to separate in two tables, one called something like "UserTable" containing an primary key Id and the @TableName, and another called something like "UserValues" containing your @Id and @Name and also a UserTableId to connect with the other table.

This way you don't let the users create tables in your database which is really not a wanted design!

Hope this helps