【问题标题】:Multiple conditional ANDs in SQL WHERESQL WHERE 中的多个条件 AND
【发布时间】:2020-06-11 22:36:47
【问题描述】:

我目前在 Java 中使用 String 来运行 SQL 语句

String fruitName = "apple";
String colorOfFruit = a < b ? null : "red";
String sizeOfFruit = c > d ? null : "big";

String sql = "SELECT * FROM my_table WHERE fruit = ? " +
 if (colorOfFruit != null) sql += "AND color = ? ";
 if (sizeOfFruit != null) sql += "AND size = ? "
 sql += "ORDER BY fruit";


int i = 1;
PreparedStatement stmt = databaseConnection.prepareStatement(sql)
stmt.setString(i++, fruitName);
if (colorOfFruit != null) stmt.setString(i++, colorOfFruit);
if (sizeOfFruit != null) stmt.setString(i++, sizeOfFruit);

ResultSet rs = stmt.executeQuery();

有什么方法可以将其转换为可以在 Java 中使用 CallableStatement 运行的 SQL 查询?我正在考虑创建一个存储过程,但我不确定如何有条件地拥有 AND 语句。

CREATE PROCEDURE MyProcedure
    @fruitName NVARCHAR(50),
    @colorOfFruit NVARCHAR(50),
    @sizeOfFruit NVARCHAR(50)
AS
BEGIN
    SELECT * FROM my_table WHERE fruit = @fruitName
    -- add an and statement here if @colorOfFruit is not null
    -- add another and statement here if @priceOfFruit is not null
    ORDER BY fruit
END

【问题讨论】:

    标签: java sql sql-server sql-server-2008 java-8


    【解决方案1】:

    只需使用AND/OR 逻辑例如

    如果 参数为空 OR 参数 = 列值 例如

    SELECT *
    FROM my_table
    WHERE fruit = @fruitName
    -- add an and statement here if @colorOfFruit is not null
    and (@colorOfFruit is null or color = @colorOfFruit)
    -- add another and statement here if @sizeOfFruit is not null
    and (@sizeOfFruit is null or Size = @sizeOfFruit)
    ORDER BY fruit
    

    【讨论】:

      【解决方案2】:

      您当前的解决方案是最好的,因为它允许 SQL 优化器选择最佳访问计划。

      不过,我会使用三元条件运算符,并记得使用 try-with-resources:

      String sql = "SELECT *" +
                    " FROM my_table" +
                   " WHERE fruit = ?" +
                 (colorOfFruit == null ? "" :
                     " AND color = ?") +
                 (sizeOfFruit == null ? "" :
                     " AND size = ?") +
                   " ORDER BY fruit";
      try (PreparedStatement stmt = databaseConnection.prepareStatement(sql)) {
          int paramIdx = 0;
          stmt.setString(++paramIdx, fruitName);
          if (colorOfFruit != null)
              stmt.setString(++paramIdx, colorOfFruit);
          if (sizeOfFruit != null)
              stmt.setString(++paramIdx, sizeOfFruit);
          try (ResultSet rs = stmt.executeQuery()) {
              while (rs.next()) {
                  // code here
              }
          }
      }
      

      【讨论】:

      • 我需要使用存储过程,因为我使用的实际 sql 很长。我刚刚为这个问题创建了一个小样本。谢谢你的评论。
      • @lzdyzydy 为什么 SQL 语句的大小很重要?
      猜你喜欢
      • 2017-06-11
      • 1970-01-01
      • 2022-01-19
      • 2016-11-18
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      相关资源
      最近更新 更多