使用
string sql = @"
SELECT TOP 50 *
FROM Log
ORDER BY Date desc";
return context.Database.SqlQuery<Log>(sql).ToList();
工作,但当我试图插入像
这样的参数时string sql = @"
SELECT TOP @top *
FROM Log
ORDER BY @order";
List<object> parameters = new List<object>();
parameters.Add(new SqlParameter("top", top)); //top is int with value 50
parameters.Add(new SqlParameter("order", order)); //order is string with value Date desc
return context.Database.SqlQuery<Log>(sql, parameters.ToArray()).ToList();
我得到了
“附加信息:'@ top'附近的语法不正确。”。
哪里错了?
答案 0 :(得分:3)
按以下方式重新排列您的查询
string sql = @"
SELECT TOP (@top) *
FROM Log
ORDER BY @order";
修改强>
string sql = @"
SELECT TOP @top *
FROM Log
ORDER BY ";
sql += order;
List<object> parameters = new List<object>();
parameters.Add(new SqlParameter("top", top)); //top is int with value 50
return context.Database.SqlQuery<Log>(sql, parameters.ToArray()).ToList();