0

Here's my code. I am not able to set TableName variable, it is throwing an exception Must declare the table variable "@TableName"

public DataTable getAllDataFromTable(String TableName)
        {

            cmd.CommandText = "select * from @TableName";
            cmd.Parameters.AddWithValue("@TableName", TableName);
            da.SelectCommand = cmd;
            da.Fill(dt);
            return dt;

        }
Charu
  • 2,679
  • 6
  • 35
  • 52

1 Answers1

0

You cannot use a parameter in that fashion. The best way to implement what you are looking for is to use a string.Format() method to create your select statement. The only real draw back is the fact you open the method up to SQL Injection.

public DataTable getAllDataFromTable(String TableName) {

        cmd.CommandText = string.Format("select * from {0}", TableName)";
        da.SelectCommand = cmd;
        da.Fill(dt);
        return dt;

    }

Here is a similar thread.

Table name and table field on SqlParameter C#?

Community
  • 1
  • 1
Nico
  • 12,493
  • 5
  • 42
  • 62
  • Ok, does this mean i can use parameters only for variables in where clause? – Charu May 17 '12 at 06:43
  • 1
    @Charu Yes, paramaeters are to pass data into your SQL query and does not modify your actual sql query. Now again only for data, so column names, table names, database names will not work. Cheers.. – Nico May 17 '12 at 06:45