简体   繁体   中英

Find rows which are in a row with comma separated values same table sql

i have a table which contains comma separated values some thing like

id locs
1  a,s,d,f
2  s,d,f,a
3  d,s,a,f
4  d,f,g,a
5  a,s,e
6  f,d

i need out put as 1,2,3,6 in sql server when i have taken comma separated string of id 1.

that means i have taken locs of id 1 and separated with comma, now i want all the ids which contains the separated values of id 1.

Note: I know i don't have to keep comma separated values in table but its happened.

Hope i was clear with my question.

If I understand you correctly, you need to return the id value of all the rows that has at least one of the comma separated values from the locs column of the row you selected. Since this is a poor database design there can only be an ugly solution to this problem. Start by creating a user defined function to split a comma separated values into a table. there are many ways to do it, this is the first that google found .

DECLARE @Values varchar(max)
SELECT @Values = Locs 
FROM Table WHERE Id = @Id 

SELECT Id
FROM Table INNER JOIN dbo.Split(@Values) SplitedString
ON( '%,'+ SplitedString.s+',%' LIKE ',' + Locs + ',')
declare @tb table (id int, locs varchar(50))
insert into @tb values(1,  'a,s,d,f'),
(2,'s,d,f,a'),
(3,'d,s,a,f'),
(4,'d,f,g,a'),
(5,'a,s,e'),
(6,'f,d')
declare @cta varchar(20)='s,d,f,a'
;with cte0(id,col2)
as
(
select id,t.c.value('.','varchar(max)') as col2 from (select id,x= cast('<t>'+replace(locs,',','</t><t>') +'</t>'  as xml) from @tb) a cross apply x.nodes('/t') t(c)
)
select distinct id from cte0 where  @cta  like '%'+col2+'%' and id not in( select distinct id from cte0 where @cta not like '%'+col2+'%')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM