Split function in SQL Server 2008

前端 未结 4 1438
孤城傲影
孤城傲影 2020-11-28 15:29

I have Table1 with columns like this:

+--+------+
|ID|Name  |
+--+------+
|1 |MSSQL |
+--+------+
|2 |MySQl |
+--+------+
|3 |Oracle|
+--+------         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 16:03

    You are asking for a split function but you do not have to split your values to get the result you want.

    This query builds the comma separated names list in a correlated subquery using the for xml trick to concatenate values. It uses like to figure out what values to use from Table1 for each row in Table2.

    select (
           select ', '+T1.Name
           from Table1 as T1
           where ','+T2.Databasename+',' like '%,'+cast(T1.ID as varchar(10))+',%'
           for xml path(''), type
           ).value('substring(text()[1], 3)', 'varchar(max)') as Databasenames
    from Table2 as T2
    

    SQL Fiddle

提交回复
热议问题