我有以下语句在使用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);
}
上下文创建正确(用于程序的其他部分),表名拼写正确。根据微软的文档,这应该可以从表中删除最大数量的记录,但却引发了一个异常:
System.Data.SqlClient.SqlException:@p0附近的语法不正确。
我反复检查了ExecuteStoreCommand
的语法,没有发现任何错误。
如何在这样的DELETE
语句中使用TOP
子句?
将参数传递给TOP
时,需要将其括在括号中:
int count = context.ExecuteStoreCommand(string.Concat("DELETE TOP ({0}) FROM ", name), top);
当从Java执行SELECT TOP
语句时,我在一篇类似但不相关的帖子中找到了答案(MS SQL异常:'@P0'附近的语法不正确)。
如果将TOP
作为参数传递,则"SQL Server要求在其参数周围放置圆括号"。
因此,有效的代码是:
int top = 1000;
string name = "StagingTable";
using (var context = CreateObjectContext())
{
int count = context.ExecuteStoreCommand(string.Concat("DELETE TOP ({0}) FROM ", name), top);
}
谢谢,安多马尔。