java - SQL WHERE 中的多个条件 AND

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

我目前正在 Java 中使用字符串来运行 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

最佳答案

只需使用AND/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

关于java - SQL WHERE 中的多个条件 AND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60441294/

相关文章:

sql - 如何只比较月份和年份,而不是完整的日期?

sql - 输入日期时如何在oracle中获取分区名称

sql - 带日期时间的 MSSQL 转换不输出 Z 时区指示符

asp.net - 处理 SQL Server 中的 SortOrder 字段

sql-server - Laravel homestead中如何连接MSSQL?

java - 将 int32_t 编码为字节数组

java - 为什么我的循环 GUI 计时器没有显示?

java - HSQLDB 意外标记 :?

java - 即使对 SET_ALARM 使用 <uses-permission> 也会获得权限拒绝?

MYSQL 使用 WHERE 条件连接表