I am trying to use a parametrized query which takes 2 column names and a table name and retrieves the data from a sql server DB.
The problem is it is not possible to parametrize the table name so i found a solution using a sqlcommandbuilder.quoteIdentifer(tablename) and this bit works...but apparently they don't play nice together.
I get exception containing a single word which is the column name If i put the column name by hand it works.
What is wrong here?
public List<ItemsWithDescription> GetItemsFromDB(string name, string desc, string tableName)
{
List<ItemsWithDescription> items = new List<ItemsWithDescription>();
try
{
Status = 1;
SqlCommandBuilder builder = new SqlCommandBuilder();
cmd = new SqlCommand("Select @Name, @Desc from "+ builder.QuoteIdentifier(tableName), conn);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Desc", desc);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
items.Add(new ItemsWithDescription(dr[name].ToString(), dr[name].ToString() + " | " + dr[desc].ToString()));
}
}
items.Sort((x, y) => string.Compare(x.Item, y.Item));
}
catch
{
Status = -1;
}
return items;
}
Edit: This works but I would prefer to know why both can't be used together:
cmd = new SqlCommand("Select" +
builder.QuoteIdentifier(name) + "," +
builder.QuoteIdentifier(desc) + "from " +
builder.QuoteIdentifier(tableName), conn);