Android Question [Solved] SQL - IN operator

udg

Expert
Licensed User
Longtime User
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?

TIA
 

Mahares

Expert
Licensed User
Longtime User
but with the Countries' list built at runtime and made up of any number of items (i.e 1 to 20).
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')
 
Upvote 0

udg

Expert
Licensed User
Longtime User
@Mahares : that's exactly what I meant with " I know that I could construct the whole statement once .."
@aeric : can you please show an example?
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
Or you can select values from another table
SQL:
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)
 
Upvote 0

udg

Expert
Licensed User
Longtime User
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
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…