1

I have table tableA as below:

+--------+----------------------+
|   Id   |          Ref         |
+--------+----------------------+
|    1   |    RN1-102,RN2-103   |  
|    2   |    RN1-106           |
|    3   |    RN2-203           |
|    4   |    NULL              |
|    5   |    RN1-104|,RN2-107  |
|    6   |    RN1-101,RN2-105   |
|    7   |    RN1-100,RN2-109   |
+--------+----------------------+

I need a output (distinct Ref from tableA) as below:

+--------------------+
| Distinct Ref data  |
+--------------------+
|      RN1-100       |
|      RN1-101       |
|      RN1-102       |
|      RN1-104       |
|      RN1-106       |
|      RN2-103       |
|      RN2-105       |
|      RN7-107       |
|      RN2-109       |
|      RN2-203       |
+--------------------+

I tried with below query:

select distinct Ref from tableA

Please help me out..

Mythily
  • 57
  • 1
  • 4
  • 10

3 Answers3

1

Try using this

SELECT distinct Split.a.value('.', 'VARCHAR(100)') REF
           FROM   (select ID,Cast ('<M>'
                                + replace(Replace(REF, ',', '</M><M>'),'&','&amp;')
                                + '</M>' AS XML) AS Data from #Table) AS A
                  CROSS APPLY Data.nodes ('/M') AS Split(a) 
PP006
  • 681
  • 7
  • 17
0

This question is similar to this question I answered before. I offered two approach in that answer, one is using recursive another not.

But if you already have a table stores the ref keys, you have the third choice like this:

create table ref_table (ref varchar(10), ref_name varchar(100), primary key (ref));

select
    r.ref
from 
    ref_table r
where 
    EXISTS (
        select 1 
        from tableA a
        where a.ref like '%'+r.ref+'%'  -- or ','+a.ref+',' like '%,'+r.ref+',%' 
        )

SQL FIDDLE DEMO

Community
  • 1
  • 1
Jaugar Chang
  • 3,176
  • 2
  • 13
  • 23
0
SELECT distinct Split.a.value('.', 'VARCHAR(100)') REF
           FROM   (select ID,Cast ('<M>'
                                + replace(Replace(REF, ',', '</M><M>'),'&','&amp;')
                                + '</M>' AS XML) AS Data from #Table) AS A
                  CROSS APPLY Data.nodes ('/M') AS Split(a)
Mythily
  • 57
  • 1
  • 4
  • 10