Search code examples
c#sqlado.netparameterized

get data from variable table and return as datatable c#


I need to get retrive all of the data from specified tables and I don't need the data to be strongly typed so I am returning it as a data table.

public DataTable GetByTypeName(String t)
    {
        var type = Type.GetType(t);

        var dt = new DataTable();

        using (var sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["MasterPlanConnectionString"].ConnectionString))
        {
            var sqlComm = new SqlCommand("SELECT * FROM @table", sqlConn);
            sqlComm.Parameters.AddWithValue("@table", type.Name);

            sqlConn.Open();

            var dr = sqlComm.ExecuteReader(CommandBehavior.CloseConnection);

            dt.Load(dr);
        }

        return dt;
    }

When I run this I get the error

System.Data.SqlClient.SqlException was unhandled by user code
Message=Must declare the table variable "@table".

I cannot figure out why this isn't working as I have declared @table. I know this method is open to some bad sql attacks so I plan to add in some protection about exactly what types can be queried against.


Solution

  • You can construct your query dynamically - (should be ok over here, but may expose your query to sql injection)

            var query = String.Fromat("Select * from [{0}]", type.Name);
            var sqlComm = new SqlCommand(query, sqlConn);
            /*sqlComm.Parameters.AddWithValue("@table", type.Name);*/