如何修复 "Incorrect syntax near ')'"。当查询中没有 ) 时

How to fix "Incorrect syntax near ')'". when there is no ) in the query

我正在尝试 运行 使用 Dapper 对我的数据库进行查询,但是,抛出了一个异常。异常信息为

Incorrect syntax near ')'

让我感到困惑的部分是我在整个查询中没有右括号。它曾经有一些,但我一直在简化它直到我得到这个:

select i.id as EmployeeReviewId
from @ReviewIds i

这仍然会导致错误。

@ReviewIds 是一个 table 值参数,只有一列,一个名为 id 的 int 列。

我是这样调用函数的:

await connection.QueryAsync<FooInfo>(sql, new { reviewIds });

其中 FooInfo 是具有 EmployeeReviewId 属性 的对象,reviewIdsint.

的可枚举对象

我不得不假设这与我使用 Dapper 的方式有关。

有人知道如何解决这个问题吗?

您可能错误地传递了用户定义的 table 参数。您必须将其作为 DataTable 传递,而不是作为简单数组传递。一个最小的工作示例是

public class FooInfo
{
    public int EmployeeReviewId { get; set; }
}

class Program
{
    static async Task Main(string[] args)
    {
        using (var connection =
            new SqlConnection("Persist Security Info=False;Integrated Security=true;Initial Catalog=YOUR_DB_NAME;Server=."))
        {
            var result = await connection.QueryAsync<FooInfo>("select i.id as EmployeeReviewId from @ReviewIds i", new
            {
                ReviewIds = CreateTableType(new[] {1, 2, 3})
            });
            Console.WriteLine(result);
        }
    }

    private static DataTable CreateTableType(IEnumerable<int> nums)
    {
        var t = new DataTable();
        t.SetTypeName("dbo.ArrayOfInt");
        t.Columns.Add("id");
        foreach (var num in nums)
        {
            t.Rows.Add(num);
        }
        return t;
    }
}

其中dbo.ArrayOfInt是

CREATE TYPE dbo.ArrayOfInt AS TABLE  
(  
id int NOT NULL
)