Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Bagaimana cara mendapatkan teks yang dipisahkan koma yang sesuai untuk serangkaian kode yang dipisahkan koma?

Mungkin ada solusi yang lebih sederhana untuk melakukan ini, tetapi inilah salah satu caranya.

Struktur tabel

create table Locations(LocationID int, Location varchar(50))
create table OtherTable(ID int, Locations varchar(max))

Data uji

insert into Locations values(1, 'Location <1>')
insert into Locations values(2, 'Location <2>')
insert into Locations values(3, 'Location <3>')
insert into Locations values(4, 'Location <4>')
insert into Locations values(5, 'Location <5>')

insert into OtherTable values (1, '')
insert into OtherTable values (2, '2')
insert into OtherTable values (3, '1, 3 ,5')

Kueri

;with cte as
(
  select 
    T.ID,
    coalesce(L.Location, '') as Location
  from OtherTable as T
    cross apply
      (select cast('<r>'+replace(T.Locations, ',', '</r><r>')+'</r>' as xml)) LocXML(XMLCol)
    cross apply
      LocXML.XMLCol.nodes('r') LocID(IDCol) 
    left outer join Locations as L
      on L.LocationID = LocID.IDCol.value('.', 'int')
)
select
  C1.ID,
  stuff((select ', '+C2.Location
         from cte as C2 
         where C1.ID = C2.ID
         for xml path(''), type).value('text()[1]', 'nvarchar(max)'), 1, 2, '') as Locations
from cte as C1
group by C1.ID

Hasil

ID  Locations
--- ----------------------------------------
1   
2   Location <2>
3   Location <1>, Location <3>, Location <5>



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Memutakhirkan SQL Server 2000 hingga 2005 atau 2008 - DTS ke SSIS

  2. sql:nilai baris sebagai kolom

  3. replikasi antara penerbit offline dan pelanggan online?

  4. Cara Menghindari Monitor Aktivitas Menyakiti Kinerja SQL Server Anda

  5. Hasilkan nama acak di sql