首页 > 解决方案 > SQL 查询未按预期执行:Visual Studio

问题描述

我有一个程序,它使用查询从数据库中提取搜索结果来填充页面。用户可以从下拉菜单中选择多个选项,它只会返回包含特定选择的结果,但是当我尝试使用它时,它会返回不包含用户选择的结果。这是我使用的查询之一(其他查询非常非常相似,遇到同样的问题)。

Dim o = From c In myContext.Competitions.Include("CodeJusticeBranches").Include("CodeJusticeLocations").Include("CodeCompetitionTypes").Include("CodePositionTypes").Include("CompetitionPositions") _
        Where (pstrCompNum Is Nothing OrElse c.comp_number = pstrCompNum) _
          And (pstrCompYear Is Nothing OrElse c.comp_number.Length <= 8 And c.comp_number.StartsWith(strYear) = True) _
           Or (pstrCompYear Is Nothing OrElse c.comp_number.Length > 8 And c.comp_number.Substring(6, 2) = strYear) _
          And (pstrCompTypeId Is Nothing OrElse c.CodeCompetitionTypes.code_ct_id = CInt(pstrCompTypeId)) _
          And (pstrBranchId Is Nothing OrElse c.CodeJusticeBranches.code_branch_id = CInt(pstrBranchId)) _
          And (pstrPosTypeId Is Nothing OrElse c.CodePositionTypes.code_pos_type_id = CInt(pstrPosTypeId)) _
        Order By c.comp_number _
        Select c

If o.Count > 100 Then
    Throw New FaultException("Your search has returned more than 100 Competitions - please narrow your search")
Else
    Return o.ToList
End If

数据库的设置方式,如果没有选择年份,如我只选择一个branchId,PosTypeId或CompTypeId,结果超过100个,所以不会返回列表。那不是问题。The problem comes when a year is selected as well as the other parameters (we're ignoring CompNum since we want multiple results, not a specific Num).

发生的情况是该列表将包含该年度的所有元素,甚至不查看其他参数。

例如,如果我要求它查找 2019 年分支为 1、PosType 为 2 和 compType 为 3 的所有元素,它将返回 2019 年的所有元素。它将忽略其他搜索标准。

任何建议将不胜感激。谢谢。

标签: sqlvb.netvisual-studio-2012

解决方案


在 pstrCompYear 过滤器前后添加括号,因此 Or 不会影响其余条件。

And ((pstrCompYear Is Nothing OrElse c.comp_number.Length <= 8 And c.comp_number.StartsWith(strYear) = True) _
       Or (pstrCompYear Is Nothing OrElse c.comp_number.Length > 8 And c.comp_number.Substring(6, 2) = strYear)) _

推荐阅读