Hi all,
is there a way in pure SQL to construct a WHERE clause using the IN operator where its list is of variable length?
I mean something like:
B4X:
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
but with the Countries' list built at runtime and made up of any number of items (i.e 1 to 20).
I know that I could construct the whole statement once I've inspected the input parameters so to know beforehand how many "?" I should use on case-by-case basis.
But what about SQL language?
You can build your IN clause with StringBuilder like this:
B4X:
Dim MyList As List
MyList.Initialize
MyList.AddAll(Array As String("Germany", "France", "UK", "Israel"))
Dim sb As StringBuilder
sb.Initialize
sb.Append( " IN(")
For i= 0 To MyList.size -1
Dim f As String =MyList.Get(i)
If i = MyList.Size-1 Then
sb.Append($"'${f}')"$)
Else
sb.Append($"'${f}',"$)
End If
Next
Log(sb.ToString) 'displays: IN('Germany','France','UK','Israel')
CREATE TABLE `countries` (
`country` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `countries` (`country`) VALUES
('Germany'),
('France'),
('UK');
SELECT * FROM Customers
WHERE Country IN
(SELECT country FROM Countries)
OK, thanks.
So my options are:
- fill on the fly a temporary table and use it like you did on post #6
- follow the StringBuilder path and construct on the fly a Select statement based on the parameters received