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

Wrong query: Incorrect syntax near ')'

我有 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;
}

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

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

我不确定发生了什么。

那是因为 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

您的查询“if exists (select * from T_TicketGroupsToChangePrice where SubTypeId = @SubTypeId and DateId = @dateId and UserId = @userId)” return 一些数据,如果 table 有一些数据,那么它需要一些工作。就像编程中的 if else 条件一样,我们可以将其修改为:

if exists 
(select * from T_TicketGroupsToChangePrice where SubTypeId = @SubTypeId and DateId = @dateId and UserId = @userId) 
Print 'Have Data'
 else 
Print 'Don't Have data'

重写您的代码:

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) Print '**your code to execute if exist data**' else Print '**your code to execute if doesnot exist data**'";
    using (var conn = CreateSqlConnection())
    try
    {
        int rows = conn.Execute(sql, ticketGroups.Select(g => new { SubTypeId = g, UserId = userId, DateId = dateId }));
        if (rows > 0)
            bRetVal = true;
    }
    catch (SqlException ex)
    {
        throw new Exception("Error", ex);
    }

    return bRetVal;
}

这个 link 会帮助你更多: https://dba.stackexchange.com/questions/30159/exist-select-from-my-table

如果您的结果取决于行数而不是 return 从 SQL 编辑的内容,您可以试试这个:

if exists ([whatever]) select 1

这行得通,因为如果没有匹配值,则不会 return 编辑任何记录集,并且您受影响的记录数为零。

您也可以尝试更简单的方法:

select 1 
from T_TicketGroupsToChangePrice 
where SubTypeId = @SubTypeId 
  and DateId = @dateId 
  and UserId = @userId;

但这有一个缺点,即 return无论您有多少条记录,都需要一行。这可能很多,具体取决于应用程序和上下文,并且在任何情况下您都不想提取不打算使用的数据。

我不推荐 CASE 语句,因为 SELECT CASE EXISTS ([whatever]) THEN 1 END 仍然会 return 一条记录,即使不存在任何记录,您受影响的记录数也将为 1。

你原来的问题SQL,顺便说一句:声明不完整。你说的是 "if exists ...",但你永远不会用 "then" 的等价物来结束它。你需要说 "if exists() select 1" 或类似的东西。