This question already has an answer here:
UPDATE: Someone marked this question as duplicate of How do I split a string so I can access item x. But it's different, my question is about Sybase SQL Anywhere, the other is about MS SQL Server. These are two different SQL engines, even if they have the same origin, they have different syntax. So it's not duplicate. I wrote in the first place in description and tags that it's all about Sybase SQL Anywhere.
I have field id_list='1234,23,56,576,1231,567,122,87876,57553,1216'
and I want to use it to search IN
this field:
SELECT *
FROM table1
WHERE id IN (id_list)
id
isinteger
id_list
isvarchar/text
But in this way this doesn't work, so I need in some way to split id_list
into select query.
What solution should I use here? I'm using the T-SQL Sybase ASA 9 database (SQL Anywhere).
Way I see this, is to create own function with while loop through, and each element extract based on split by delimiter position search, then insert elements into temp table which function will return as result.
You use text in your query and this is not going to work. Use dynamic query.
The dynamic query approach would look like this:
Good contribution from bsivel answer, but to generalise it (for other separators than a comma), then the line
must become
The first version will only work for comma-separated lists.
This can be done without using dynamic SQL but you will need to create a couple of supporting objects. The fist object is a table valued function that will parse your string and return a table of integers. The second object is a stored procedure that will have a parameter where you can pass the string (id_list), parse it to a table, and then finally join it to your query.
First, create the function to parse the string:
Now create your stored procedure:
Execution Example:
I hope this helps...
Like Mikael Eriksson said, there is answer at dba.stackexchange.com with two very good solutions, first with use of
sa_split_list
system procedure, and second slower withCAST
statement.For the Sybase SQL Anywhere 9
sa_split_list
system procedure not exist, so I have madesa_split_list
system procedure replacement (I used parts of the code from bsivel answer):Execute the same way as
sa_split_list
with default delimiter,
:or with specified delimiter which can be changed: