Parameterized query ado.net issue
I am using this query for pagination
string selectStatement = "SELECT * FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY @sortMember @sortDirection ) AS RowNum, * FROM School) AS Rows WHERE RowNum > @pageFrom AND RowNum < @pageTo ";
command.Parameters.Add("@sortDirection", System.Data.SqlDbType.NVarChar, 50);
command.Parameters["@sortDirection"].Value = cmd.SortDescriptors.Count == 0 ? "" : cmd.SortDescriptors[0].SortDirection == System.ComponentModel.ListSortDirection.Ascending ? "" : "DESC";
if sortDirection is "" i get an exception. if u use it like this it works fine but i want to make it p开发者_开发知识库arameterized query. what is the solution?
string selectStatement = string.Format("SELECT * FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY @sortMember {0} ) AS RowNum, * FROM School) AS Rows WHERE RowNum > @pageFrom AND RowNum < @pageTo ",System.ComponentModel.ListSortDirection.Ascending ? "" : "DESC);
The exception i get is :Incorrect syntax near '@sortDirection'.
You can't parameterise things like table-names, columns, order-by, etc. They are the query. You will need to white-list the expected values (to avoid SQL injection) and concatenate it into the query directly (which is what your string.Format
usage does).
At the moment, the order-by is on the vale of the variable, which doesn't change per-row. Essentially, the sort (as written) is ignored.
That's not how parameters work. You have to dynamically build your query's string.
精彩评论