0

I am trying to pass the variable as a table name in sql command text. This is code i tried

string tableName = string.Empty;

for (int m = dateDebut.Month; m <= dateFin.Month; m++)
{
    sqlCommand.Parameters.Clear();
    tableName = "DynamicPosition" + m;

    sqlCommand.CommandText = "SELECT ProfileId, FloorId FROM @tableName WHERE ProfileId = @profileId AND LastUpdate >= @dateDebut AND LastUpdate <= @dateFin";

    sqlCommand.Parameters.AddWithValue("@tableName", tableName);
}

This is the error I am getting

Must declare the table variable \"@tableName\"

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kenzo
  • 1,767
  • 8
  • 30
  • 53

1 Answers1

2

Parameter passing is for passing in constant ("literal") values. You are not allowed to pass in anything else. This includes:

  • server/database/schema/table names
  • column names
  • function names
  • operators
  • SQL keywords

Your only real solution is to "munge" the query string, substituting the table name before you pass it to the database. Alternatively, you can design the database so this is not necessary.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786