2

I have a column (data) in database having values like

id     name     data
1     jatin    1,11,15
2     harsh     3,5,11

what can I do if I want to get the names of persons having 11 in data column??

thanks

1
  • looking for my sql only. Commented Oct 3, 2013 at 8:43

2 Answers 2

1

On MS SQL Server you cannot use the FIND_IN_SET function, and would have to do something like this instead:

SELECT * FROM MyTable
WHERE ',' + Data + ',' LIKE '%,11,%'

I've added the commas in front and in the end of the Data column, to ensure that the LIKE operator works, even if "11" is at the beginning or the end of the string.

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

Comments

0

You can use this function:

CREATE FUNCTION CSV2Table (@var VARCHAR(max))
RETURNS TABLE
AS
RETURN (
        -- Recursive CTE
        WITH CSV(pop, variable) AS (
                -- Base case
                SELECT CASE 
                        WHEN charindex(',', @var) > 0
                            THEN substring(@var, 1, charindex(',', @var) - 1)
                        ELSE @var
                        END,
                    CASE 
                        WHEN charindex(',', @var) > 0
                            THEN substring(@var, charindex(',', @var) + 1, len(@var) - charindex(',', @var) + 1)
                        ELSE ''
                        END

                UNION ALL

                -- Recursive
                SELECT CASE 
                        WHEN charindex(',', CSV.variable) > 0
                            THEN substring(CSV.variable, 1, charindex(',', CSV.variable) - 1)
                        ELSE CSV.variable
                        END,
                    CASE 
                        WHEN charindex(',', CSV.variable) > 0
                            THEN substring(CSV.variable, charindex(',', CSV.variable) + 1, len(CSV.variable) - charindex(',', CSV.variable) + 1)
                        ELSE ''
                        END
                FROM CSV
                WHERE len(CSV.variable) > 0
                )
        SELECT pop
        FROM CSV
        )
GO

and do something like:

SELECT * FROM <TABLE> WHERE EXISTS(SELECT TOP 1 1 FROM dbo.CSV2Table(data) WHERE POP = '11')

Comments

Your Answer

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