我需要处理一个查询字符串并从中创建记录。
最初格式是这种格式的转义字符串:
relativeFilePath1^relativeFilePath2^relativeFilePath3^relativeFilePath4
使用%5E转义^字符。用于在此位置拆分字符串,创建临时表,在其中插入所有内容并从那里触发插入。
DECLARE @SplittetList TABLE(ID int Identity(1,1), fPath nvarchar(max));
INSERT INTO @SplittetList SELECT * FROM Schema.fnSplit('relativeFilePath1%5ErelativeFilePath2%5ErelativeFilePath3%5ErelativeFilePath4', '%5E')
--additional processing
现在格式即将更改,以便在每个文件路径之后,还有该文件的其他元数据字段,也用^字符分隔。如果我现在拆分这个我得到这样的结果:
ID | fPath
---------------------
1 | relativeFilePath1
2 | metadata1
3 | relativeFilePath2
4 | metadata2
5 | relativeFilePath3
6 | metadata3
n | ...
如何转换此列表,以便结果是这种格式的一组数据:
filepath | metadata
----------------------------------
relativeFilePath1 | metadata1
relativeFilePath2 | metadata2
relativeFilePath3 | metadata3
...
答案 0 :(得分:1)
DECLARE @Data table
(
ID int identity(1,1),
fPath nvarchar(max)
)
insert @Data values
('relativeFilePath1'),('metadata1'),('relativeFilePath2'),('metadata2'),('relativeFilePath3'),('metadata3')
-- ROW_NUMBER to ensure the ID is continuous
;with data as
(
select *,
(ROW_NUMBER() OVER (ORDER BY Id)+1)/2 as grp,
(ROW_NUMBER() OVER (ORDER BY Id)+1)%2 as columnno
from @Data
)
-- Subquery verison
select
(select fPath from data where grp = d.grp and columnno = 0) as filepath,
(select fPath from data where grp = d.grp and columnno = 1) as metadata
from data d group by grp
-- Inner join version
--select a.fPath, b.fPath from data a inner join data b on a.grp = b.grp
--where a.columnno = 0 and b.columnno = 1