-1

When an Insert query is used, parameters will work just fine because it is for values, but if I were to use parameters for Create or Select query for table names, it just wont happen because apparently table names has to be static.

#For example

 SqlCommand myCommand = new SqlCommand("create table @1 ([BACK_LANG] varchar(50)");
                    myCommand.Connection = myDatabase;
                    myCommand.Parameters.AddWithValue("@1", this.getName()); //it was already set
                    myCommand.ExecuteNonQuery();

But I do need to use Select/Create query with parameters, because I'll be selecting from the table they have created.

Sadly I couldn't come up with a solution and had to use non-parameter way, which is vulnerable to SQL Injections, the google search I've done past days didn't help me.

How do i use Create/Select Queries in SQL Server with .NET for table names?

beriscen
  • 17
  • 5

1 Answers1

1

You can't pass an object name as a parameter directly to the statement like that. You can still use a parameter but the command will have to be something like this:

(@"declare @sql nvarchar(max) = N'create table dbo.'
   + QUOTENAME(@1) + N'([BACK_LANG] varchar(50));';
  EXEC sys.sp_executesql @sql;")

Or just build the string in C#, using SqlCommandBuilder's QuoteIdentifier(this.getName()) which provides similar protection as QUOTENAME().

For more on SQL injection: Dynamic SQL

Charlieface
  • 52,284
  • 6
  • 19
  • 43
Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490