SQL Server 2005:如何从跨 2 列的逗号分隔数据创建新列

SQL Server 2005: How to create a new column from comma-delim data across 2 columns

我需要将这些数据并排显示。

换句话说就是这样...

NewColumn
TECNQ221 3/03/2017 11:10am, TECNQ174 3/03/2017 12:59pm, TECNQ174 3/03/2017 2:04PM, etc

所以基本上将 ModificationStaff 中的第一个元素放在 ModificationDates 旁边并用逗号分隔,所有元素都在 VARCHAR(MAX) 中的单个列中。

谢谢

创建一个接受两个参数 ModificationStaff 和 ModificationDates 的函数。在此函数内拆分 modificationstaff 和 modificationdate。然后组合拆分对象的相同位置。 (要拆分文本,请使用此方法:T-SQL split string)。该函数的返回值将为

TECNQ221 3/03/2017 11:10am、TECNQ174 3/03/2017 12:59pm、TECNQ174 3/03/2017 2:04PM 等
在 selection (select datasaved, staffid, testfunction(ModificationStaff,ModificationDates) from db)

期间调用此函数

检查这个。

        SELECT  staffID, 
        substring(( select ','+ concat(s.Data,a.Data)  AS 'data()' 
         from
        (
            SELECT A.staffID,  
            Split.a.value('.', 'VARCHAR(100)') AS Data  ,
            row_number() over (order by (select 1) ) as rank
         FROM  
         (
             SELECT staffID,  
                 CAST ('<M>' + REPLACE(modificationstaff, ',', '</M><M>') + '</M>' AS XML) AS Data  

             FROM  #table
         ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a)
         )s  inner join

          (SELECT A.staffID,  
             Split.a.value('.', 'VARCHAR(100)') AS Data  ,
             row_number() over (order by (select 1) ) as rank

         FROM  
         (
             SELECT staffID,  
            CAST ('<M>' + REPLACE(modificationdate, ',', '</M><M>') + '</M>' AS XML) AS Data  
             FROM  #table
         ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a)
         )a   on s.rank=a.rank                       
        FOR XML PATH('') 
        ), 2, 1000)  as NewColumn
        FROM  #table

OutPut :

如果您没有 Split() 函数,请先创建它。

create FUNCTION [dbo].[Split]
(
  @delimited nvarchar(max),
  @delimiter nvarchar(100)
) RETURNS @t TABLE
(
-- Id column can be commented out, not required for sql splitting string
  id int identity(1,1), -- I use this column for numbering splitted parts
  val nvarchar(max)
)
AS
BEGIN
  declare @xml xml
  set @xml = N'<root><r>' + replace(@delimited,@delimiter,'</r><r>') + '</r></root>'

  insert into @t(val)
  select 
    r.value('.','varchar(max)') as item
  from @xml.nodes('//root/r') as records(r)

  RETURN
END