当列中的值超过1时的分隔记录

时间:2017-02-01 07:46:25

标签: sql sql-server

如果我的列包含多个值,我需要编写SQL查询来生成单独的记录。

喜欢

select * 
from tblMachine 
where pkey = 1;

这是我得到的结果:

1 C000279   EMAIL PIC       xx@yy.com;yy@xx.com

我需要编写一个查询,以便在email列中有超过1个值时生成单独的记录。

喜欢

1 C000279   EMAIL PIC       xx@yy.com
1 C000279   EMAIL PIC       yy@xx.com

这在SQL Server 2008中是否可行?

@GurV,这是我的确切查询

select distinct c.PKEY [Customer Code],
c.NAME [Customer Name],
mi.MODEL [Machine #],
(select Split.a.value('.','varchar(100)') email
from 
    (select       
        cast('<x>' + replace(m.CONTACT_EMAIL,';','</x><x>')+'</x>' as XML) as x
    from tblMachineContact m
    where mi.PKEY=m.MAC_PKEY and m.CONTACT_CATEGORY_PKEY in ('PC'))t
cross apply x.nodes ('/x') as Split(a)) [Customer Email]
from tblMachine mi
inner join tblCustomers on m.CUST_PKEY=c.PKEY
where mi.STATUS='A'

1 个答案:

答案 0 :(得分:2)

您不应在一个行和列中存储多个值。考虑规范化表格结构。

目前,您可以使用cross applyXML执行此操作。我使用列名称为col1,col2,...因为您没有提供任何架构详细信息。请根据需要更改它们。

with your_table(col1     , col2   , col3, col4) as (
    select 1 ,  'C000279'  ,'EMAIL PIC' , 'xx@yy.com;yy@xx.com'
) 
--- test data. Don't mind the above. ---

select col1, col2, col3,
    Split.a.value('.','varchar(100)') email
from 
    (select 
        col1, col2, col3,
        cast('<x>' + replace(col4,';','</x><x>')+'</x>' as XML) as x
    from your_table) t
cross apply x.nodes ('/x') as Split(a);

产地:

enter image description here

编辑:

试试这个:

select distinct 
    c.PKEY [Customer Code],
    c.NAME [Customer Name],
    mi.MODEL [Machine #],
    m.email [Customer Email]
from tblMachine mi
inner join tblCustomers on m.CUST_PKEY=c.PKEY
left join (
    select
        MAC_PKEY,
        Split.a.value('.','varchar(100)') email
    from (
        select       
            MAC_PKEY,
            cast('<x>' + replace(m.CONTACT_EMAIL,';','</x><x>')+'</x>' as XML) as x
        from tblMachineContact
        where CONTACT_CATEGORY_PKEY = 'PC'
    ) t cross apply x.nodes ('/x') as Split(a)
) m on mi.PKEY=m.MAC_PKEY
where mi.STATUS='A'