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
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
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.
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')