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
is integer
id_list
is varchar/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.
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 with CAST
statement.
For the Sybase SQL Anywhere 9 sa_split_list
system procedure not exist, so I have made sa_split_list
system procedure replacement (I used parts of the code from bsivel answer):
CREATE PROCEDURE str_split_list (in str long varchar, in delim char(10) default ',') RESULT( line_num integer, row_value long varchar) BEGIN DECLARE str2 long varchar; DECLARE position integer; CREATE TABLE #str_split_list ( line_num integer DEFAULT AUTOINCREMENT, row_value long varchar null, primary key(line_num)); SET str = TRIM(str) || delim; SET position = CHARINDEX(delim, str); separaterows: WHILE position > 0 loop SET str2 = TRIM(LEFT(str, position - 1)); INSERT INTO #str_split_list (row_value) VALUES (str2); SET str = RIGHT(str, LENGTH(str) - position); SET position = CHARINDEX(delim, str); end loop separaterows; select * from #str_split_list order by line_num asc; END
Execute the same way as sa_split_list
with default delimiter ,
:
select * from str_split_list('1234,23,56,576,1231,567,122,87876,57553,1216')
or with specified delimiter which can be changed:
select * from str_split_list('1234,23,56,576,1231,567,122,87876,57553,1216', ',')