如何修复Delete Top n命令的@p0附近的SqlException错误语法



我有以下语句在使用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);
}

谢谢,安多马尔。

最新更新