One of my code functionality requires user to enter dynamic "WHERE" clause for SQL query.
then this where clause is appended to the sql and executed on MS Sql server using Spring Boot - JDBC Template. e.g. SELECT * From Customer_Vehicles where Country in ( 'USA', 'Canada');
This Code works well if there is non Null value but it skips rows with NULL values in country column.
As per MS Sql documentation it skips NULL values as ANSI_NULLS is ON in jdbc connection (default property ).. So I tried to set the property using command "SET ANSI_NULLS OFF" using jdbc template execute method.
jdbctemplate.execute ("SET ANSI_NULLS OFF")
jdbctemplate.query("SELECT * From Customer_Vehicles where Country in ( 'USA', 'Canada')");
This solution works well for String comparison but it doesn't apply to numeric value such as mileage < 25000 e.g. SELECT * From Customer_Vehicles where Country in ( 'USA', 'Canada') and mileage < 25000
doesn't return a row if mileage is NULL.
Same is explained on MS documentation : https://learn.microsoft.com/en-us/sql/t-sql/statements/set-ansi-nulls-transact-sql?view=sql-server-ver16
Is there a way to include NULL values in the comparison (irrespective of datatype) ?
Note : users can use ISNULL function , but users are not willing to modify their SET of WHERE clauses used in legacy app.
1条答案
按热度按时间ctehm74n1#
Instead of messing around with
ANSI_NULLS
(which should never be done due to compatibility issues with newer features such as indexed views andMERGE
), instead just add a condition to your query to include nulls.