4

Is it possible to use the name of a table as a parameter in t-sql?

I want to insert data into a table, but I want one method in C# which has a parameter for the table.

Is this a good approach? I think if I have one form and I am choosing the table and fields to insert data into, I am essentially looking to write my own dynamic sql query built on the fly. This is another thing altogether which I am sure has its catches?

Thanks

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
GurdeepS
  • 65,107
  • 109
  • 251
  • 387

1 Answers1

2

Not directly. The only way to do this is through dynamic SQL - either EXEC or sp_ExecuteSQL. The latter has the advantage of query cache/re-use, and avoiding injection via parameters for the values - but you will have to concatenate the table-name itself into the query (you can't parameterise it), so be sure to white-list it against a list of known-good table names.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900