我目前正在 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/