简体   繁体   English

查找与逗号分隔的值在同一行中的行

[英]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. 当我用逗号分隔的ID为1的字符串时,我需要在sql服务器中放入1,2,3,6。

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. 这意味着我已经获取了id 1的位置并用逗号分隔,现在我想要所有包含id 1分隔值的id。

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. 如果我理解正确,则需要返回所选行的locs列中至少具有逗号分隔值之一的所有行的id值。 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 . 有很多方法可以做到, 这是google发现的第一个方法

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+'%')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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