GurdeepS
GurdeepS

Reputation: 67223

Using table names as parameters in t-sql (eg from @tblname)

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

Upvotes: 4

Views: 460

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062855

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.

Upvotes: 2

Related Questions