0

I was able to send the id successfully but trying to parametrize the table name is not possible, how can I solve this? or is there another way to send the table name as parameter in c# sql

    deleteCommand.CommandText = "delete from @tableName where rowid=@ID";
    deleteCommand.Parameters.Add(new SqlParameter("@tableName", table.Name));
    deleteCommand.Parameters.Add(new SqlParameter("@ID", table.id));
sese sese
  • 53
  • 1
  • 4
  • Does this code generate any exception? Please, post its stack trace if so. – Rafael Biz Jun 04 '21 at 22:47
  • 2
    Does this answer your question? [How can I Pass a Table Name to SqlCommand?](https://stackoverflow.com/questions/23357481/how-can-i-pass-a-table-name-to-sqlcommand) – aliassce Jun 04 '21 at 22:55

1 Answers1

0

Why dont you use string interpolation instead:

deleteCommand.CommandText = $"delete from {table.name} where rowid=@ID"; 
Gabriel Scavassa
  • 576
  • 1
  • 4
  • 21
  • 3
    Depends on where the table.Name is coming from. If it's from an unsafe source, they could inject SQL into the table name and mess things up pretty badly. – StriplingWarrior Jun 04 '21 at 23:00
  • 1
    This is not ideal because the DML doesn't allow to parameterize table names or column names, but it works fine if you are aware of SQL Injection. – Rafael Biz Jun 04 '21 at 23:15