0

Below is my SQL query :

select * 
from Table 
where col1 = @param1 and col2 = @param2

Now I want to execute that SQL query, but I am just interested in getting columns from the query, not any records.

I know I can manipulate this SQL query by finding and removing all parameterized parameters but I am just thinking that is there any way to ignore all this parameters and just execute (select * from Table).

This is how I am doing it right now :

TCommand cmd = new TCommand();
cmd.CommandText = sqlQuery;
cmd.Connection = connection;

using (var reader = cmd.ExecuteReader())
{
    reader.Read();

    var columns = reader.GetSchemaTable().AsEnumerable()
                        .Select(col => col["ColumnName"].ToString())
                        .ToArray();

    return columns;
}

I am getting this error :

Must declare the scalar variable "@param1"

I want to ignore this parameter while executing the SQL query. Is there a way to tell ADO.NET to ignore my query parameter and just execute the query?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
I Love Stackoverflow
  • 6,738
  • 20
  • 97
  • 216
  • If you are interested just in the column names, i.e. not the actual data, then look at this question - [How can I get column names from a table in SQL Server?](https://stackoverflow.com/questions/1054984/how-can-i-get-column-names-from-a-table-in-sql-server) – laika Jul 10 '17 at 14:42
  • @PanagiotisKanavos Actually user will specify this parameters in query so i cant remove them.i want to ignore this parameters when user will request columns after executing this sql query. – I Love Stackoverflow Jul 10 '17 at 14:43
  • @laika Ok then i have to extract table name from my query but i am interested in using GetSchemaTable method – I Love Stackoverflow Jul 10 '17 at 14:45

1 Answers1

0

No, you cannot ignore the query parameters. If you need to use the query above to get the column names, you should manipulate the sql by yourself. You can, for example, ignore any condition such as;

string sqlQuery="select * from Table where col1 = @param1 and col2 = @param2";
var newQuery = a.Substring(0, a.IndexOf("where"));

TCommand cmd = new TCommand();
cmd.CommandText = newQuery;
cmd.Connection = connection;

using (var reader = cmd.ExecuteReader())
{
    reader.Read();

    var columns = reader.GetSchemaTable().AsEnumerable()
                        .Select(col => col["ColumnName"].ToString())
                        .ToArray();

    return columns;
}
ali
  • 1,301
  • 10
  • 12