简体   繁体   中英

How to ignore parameters while executing a SQL query?

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM