我需要将这些数据彼此相邻显示。
换句话说就是这样......
NewColumn
TECNQ221 3/03/2017 11:10am, TECNQ174 3/03/2017 12:59pm, TECNQ174 3/03/2017 2:04PM, etc
所以基本上将ModificationStaff中的第一个元素放在ModificationDates旁边并用逗号分隔,所有这些都在单个列内的VARCHAR(MAX)内。
由于
答案 0 :(得分:2)
创建一个接受两个参数ModificationStaff和ModificationDates的函数。在这个函数里面拆分了modifystaff和modifydate。然后组合分裂对象的相同位置。 (对于拆分文本,请使用此方法:T-SQL split string)。返回该函数的值
TECNQ221 3/03/2017 11:10 am,TECNQ174 3/03/2017 12:59 pm,TECNQ174 3/03/2017 2:04 PM等 在选择期间调用此函数(从db中选择datasaved,staffid,testfunction(ModificationStaff,ModificationDates))
答案 1 :(得分:1)
检查这个。
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