我有以下语句在使用 LINQ to Entity Framework 4 的 C# 程序中失败:
int top = 1000;
string name = "StagingTable";
using (var context = CreateObjectContext())
{
int count = context.ExecuteStoreCommand(string.Concat("DELETE TOP {0} FROM ", name), top);
}
上下文创建正确(在程序的其他部分使用)并且表名拼写正确。根据 Microsoft 文档,这应该可以从表中删除最大数量的记录,但会引发异常:
System.Data.SqlClient.SqlException: Incorrect syntax near @p0.
我反复检查了 ExecuteStoreCommand 的语法,没有发现任何错误。
如何在这样的 DELETE 语句中使用 TOP 子句?
请您参考如下方法:
将参数传递给 TOP 时,需要将其括在括号中:
int count = context.ExecuteStoreCommand(string.Concat("DELETE TOP ({0}) FROM ", name), top);
