我有一个包含客户帐号和 ONE 字段的表格,其中包含多个客户备注。我需要在我的查询中将客户备注提取到单独的行项目结果中。我在下面列出了我的数据样本和我的查询的预期输出。
**TABLE**
***Customer #*** ***Customer Notes***
=====================================
25214 | 05/01/2014 - New Customer setup. - DAB |05/24/2014 - Waive Deposit. - DAB
12254 | 03/15/2013 - VIP customer. - FLH |03/23/2014 - See John if there is a
problem with customer's account. - FLH
客户备注数据字段是TEXT数据类型。如您所见,对于每个帐号,每个客户都有两个客户备注。我需要PARSE客户备注数据字段中的数据并具有以下结果:
25214 | 05/01/2014 - New Customer setup. - DAB
25214 | 05/24/2014 - Waive Deposit. - DAB
12254 | 03/15/2014 - VIP Customer. - FLH
12254 | 03/23/2014 - See John if there is a problem with customer's account. - FLH
非常感谢任何帮助!!
答案 0 :(得分:0)
如果您没有按照@Abe Miessler的建议重新设计表格,您可以尝试以下方法。
declare @table as table (AccountNumber int, Notes varchar(4000))
insert into @table values(25214,'|05/01/2014 - New Customer setup. - DAB |05/24/2014 - Waive Deposit. - DAB');
insert into @table values(12254,'|03/15/2013 - VIP customer. - FLH |03/23/2014 - See John if there is a problem with customer''s account. - FLH');
SELECT AccountNumber, Notes.n.value('.','varchar(4000)') as Notes
FROM (SELECT
AccountNumber,
CAST(replace(replace(replace((SELECT Notes FOR XML PATH('')),
'|','</n><n>|'),
'<Notes></n>','<Notes>'),
'</Notes>','</n></Notes>') AS XML) AS XNotes
FROM @table) as t
CROSS APPLY XNotes.nodes('/Notes/n') as Notes(n)
查询将Notes
列转换为XML,然后使用T-SQL XML函数将数据拉入行。
<强>输出强>
AccountNumber Notes
------------- ----------------------------------------------------------------------------
25214 |05/01/2014 - New Customer setup. - DAB
25214 |05/24/2014 - Waive Deposit. - DAB
12254 |03/15/2013 - VIP customer. - FLH
12254 |03/23/2014 - See John if there is a problem with customer's account. - FLH
<强>参考:强>
修改强> 正确转义Notes for XML中的特殊字符。添加了样本输出。
答案 1 :(得分:0)
您需要一个唯一的分隔符。我无法判断管道是否是您实际数据的一部分......所以在本例中使用日期模式:
declare @table table (CustID int,Note varchar(max))
INSERT INTO @table VALUES (25214, '05/01/2014 - New Customer setup. - DAB |05/24/2014 - Waive Deposit. - DAB')
INSERT INTO @table VALUES (12254, '03/15/2013 - VIP customer. - FLH |03/23/2014 - See John if there is a problem with customer''s account. - FLH')
SELECT CustID,
left(Note,patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%', right(Note,len(Note)-1))) as Note
FROM @table
UNION
SELECT CustID,
right(Note,len(Note) - patindex('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]%', right(Note,len(Note)-1))) as Note
FROM @table