SQL 查询未按预期执行:Visual Studio

SQL query not performing as expected : Visual Studio

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

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

数据库设置的方式,如果一年没有selected,像我这样select一个branchId,PosTypeId或者CompTypeId就有超过100个结果,所以榜单赢了不会 returned。那不是问题。当 select 年和其他参数一起使用时,问题就来了(我们忽略了 CompNum,因为我们想要多个结果,而不是特定的 Num)。

列表将包含当年的所有元素,甚至不考虑其他参数。

例如,如果我要求它在 2019 年找到分支为 1、PosType 为 2 和 compType 为 3 的所有元素,它将 return 中的所有元素2019 年。它将忽略其他搜索条件。

如有任何建议,我们将不胜感激。谢谢

在 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)) _