I have a query - SELECT <fields> FROM Account
In this, I need to add dynamic where clauses based on three conditions : Name, LastName, Age
if Name isn't empty, "SELECT <fields> FROM Account WHERE Name = 'ben'
if LastName isn't empty, "SELECT <fields> FROM Account WHERE LastName = 'stokes'
if Age isn't empty, "SELECT <fields> FROM Account WHERE Age = '25'
If none of these conditions are present, no where clause is to be added.
But if more than one of them are present, then the where clauses should be combined.
Ex: "SELECT <fields> FROM Account WHERE Name = 'ben' AND LastName = 'Stokes'
Assuming the input fields are wrapped in an object, try filtering out the empty fields and create a string based on the output, like below:
%dw 2.0
var condition = {
Name: 'Ben',
LastName: 'Stokes',
Age: 25
}
output application/json
---
"SELECT <fields> FROM Account" ++ if (!isEmpty(condition))
(" WHERE " ++
((condition filterObject ((value, key, index) -> !isEmpty(value)) // in case the values are empty, filter them out
pluck ($$ ++ " = " ++ $)) joinBy " AND ")) //a way to get the key-values pairs in a String with pluck and joinBy
else
""