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

时间:2015-07-17 10:07:15

标签: 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;
}

当我运行应用程序时,它会抛出异常:')'

附近的语法不正确

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

我不确定发生了什么。

3 个答案:

答案 0 :(得分:8)

那是因为以if开头是无效的SQL(如果你的意思是使用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

答案 1 :(得分:0)

您的查询&#34; 如果存在(从T_TicketGroupsToChangePrice中选择*,其中SubTypeId = @SubTypeId和DateId = @dateId和UserId = @userId)&#34;如果表有一些数据,则返回一些数据,因为它需要处理一些事情。就像编程中的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;
}

此链接将为您提供更多帮助: https://dba.stackexchange.com/questions/30159/exist-select-from-my-table

答案 2 :(得分:0)

如果您的结果取决于行数而不是从SQL返回的内容,您可以尝试这样做:

if exists ([whatever]) select 1

这样可行,因为如果没有匹配的值,则不会返回记录集,并且您的受影响记录数为零。

你也可以尝试一些更简单的事情:

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

但是这样做的缺点是,无论你有多少记录都会返回一行。这可能很多,取决于应用程序和上下文,并且在任何情况下,您都不想提取您将不会使用的数据。

我不建议使用CASE语句,因为SELECT CASE EXISTS ([whatever]) THEN 1 END仍然会返回一条记录,即使没有记录,您的受影响记录数也会为1。

原始SQL的问题,顺便说一句:语句不完整。你在说&#34;如果存在......&#34;但你永远不会用相当于&#34;然后&#34;完成它。你需要说&#34;如果exists()选择1&#34;或类似的东西。

相关问题