0

split string by comma in SQL and store them as split_item1, split_item2 and

select column_name from table-name where column_name = 'split_item1' or split_item2'

please post the correct syntax for this

1
  • 1
    What RDBMS you are using? RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, etc... Commented Mar 31, 2013 at 10:27

3 Answers 3

2

Assuming you are using SQL Server, you need to concatenate , from both sides of the column so you can match the value you are searching.

SELECT  *
FROM    TableName
WHERE   ',' + csvColumn + ',' LIKE '%,' + 'split_item1' + ',%' OR
        ',' + csvColumn + ',' LIKE '%,' + 'split_item2' + ',%'

Concatenation symbol differs on every dbms, CONCAT() for MySQL, || for Oracle.

Sign up to request clarification or add additional context in comments.

1 Comment

i have string in a column1 that is '001,002,003,...' and '022' is the corresponding column i.e. column2 i need to split the string according to comma separated value into 001 002 003 so that whenever i give the value 001 or 002 or 003 it should return '022' column2 i.e. select column2 from table_name where column1 like 001 or 002 or 003
0

You can use the follow code (created for sqlserver).

Create Function FUN_STRING_SPLIT(@text varchar(max), @separator varchar(10))
Returns @Result Table 
(
   POSITION INT IDENTITY(1,1) NOT NULL, VALUE VARCHAR(max) 
)
As 
Begin
    Declare @ini int = 1, @end int = 0

    While @end <= LEN(@text)
    Begin
        if @end > 0 set @ini = @end + LEN(@separator)
        if @ini > 0 set @end = CHARINDEX(@separator, @text, @ini)
        if @end = 0 set @end = LEN(@text) + 1

        Insert Into @Result (VALUE) Values (SUBSTRING(@text,@ini,@end - @ini))
    End
    Return
End

Then use like:

Select * From FUN_STRING_SPLIT('Word1,Word2,Word2,Etc..', ',');

Comments

0

select * from fromSplitStringSep('Word1 wordr2 word3',' ')

CREATE function [dbo].[SplitStringSep] 
    (
        @str nvarchar(4000), 
        @separator char(1)
    )
    returns table
    AS
    return (
        with tokens(p, a, b) AS (
            select 
                1, 
                1, 
                charindex(@separator, @str)
            union all
            select
                p + 1, 
                b + 1, 
                charindex(@separator, @str, b + 1)
            from tokens
            where b > 0
        )
        select
            p-1 zeroBasedOccurance,
            substring(
                @str, 
                a, 
                case when b > 0 then b-a ELSE 4000 end) 
            AS s
        from tokens
      )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.