【问题标题】:Split the values that exist in the same column in a table using a separator使用分隔符拆分表中同一列中存在的值
【发布时间】:2013-06-24 19:10:35
【问题描述】:

我有一张如下图所示的表格:

                     TBLContact
-------------------------------------------------
BranchId  DepartmentId  DepartmentName   Phone No
-------------------------------------------------
 BID100    DTID001       Mechanical       123654

 BID100    DTID001       Mechanical       887744

 BID101    DTID002       Automobile       045167

 BID101    DTID002       Automobile       674632

我必须以某种方式在存储过程中构建查询,以便在将“BranchId”作为参数传递给查询时,它将在单行中返回相应“BranchId”的部门电话号码,由逗号,尽管特定“BranchId”的“电话号码”存在于两行中。 例如;考虑将值“BID100”作为参数传递给查询/存储过程,查询将返回如下结果:

BranchId DepartmentId  DepartmentName   PhoneNo
---------------------------------------------------
 BID100    DT001        Mechanical    123654,887744

PS:我使用的是 SQL Server 2008。

【问题讨论】:

  • 看看this答案
  • 这种类型的转换称为枢轴。

标签: sql sql-server-2008 tsql


【解决方案1】:

这里通过 MS SQL Server 中的 XML data() 命令显示的示例是:

select PhoneNo + ', ' as 'data()' 

from TBLContact where branch_id = BID100

for xml path('')

【讨论】:

    【解决方案2】:

    以此脚本为基础

    declare @PhoneNo VARCHAR(8000) 
    
    select @PhoneNo = COALESCE(@PhoneNo+ ', ', '') + PhoneNo
    from table
    where BranchId = 'BID100'
    
    select top 1  BranchId,  DepartmentId,  DepartmentName, @PhoneNo
    from table
    where BranchId = 'BID100'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多