查询错误:')'附近的语法不正确

tes*_*icg 2 asp.net sql-server-2008 dapper

我有ASP.NET应用程序,我们使用Dapper库.产生错误的代码如下所示:

public bool CheckIfExists(IEnumerable<long> ticketGroups, long dateId, int userId)
{
    bool bRetVal = false;
    string sql = "if exists (select * from T_TicketGroupsToChangePrice where SubTypeId = @SubTypeId and DateId = @dateId and UserId = @userId)";
    using (var conn = CreateSqlConnection())
    try
    {
        int rows = conn.Execute(sql, ticketGroups.Select(g => new { SubTypeId = g, UserId = userId, dateId }));
        if (rows > 0)
            bRetVal = true;
    }
    catch (SqlException ex)
    {
        throw new Exception("Error", ex);
    }

    return bRetVal;
}
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,它会抛出异常:')附近的语法不正确

如您所见,可以有更多具有相同日期和用户的票证(IEnumerable类型).

我不确定发生了什么.

Pat*_*man 8

那是因为它不是一个有效的SQL开头if(如果你的意思是使用T-SQL,那么你必须编写整个if语句)

我认为简单case就是你所需要的:

select case
       when exists (select * from T_TicketGroupsToChangePrice where SubTypeId = @SubTypeId and DateId = @dateId and UserId = @userId)
       then 1
       else 0
       end
Run Code Online (Sandbox Code Playgroud)