我有一个 SQL Server 数据库,其中有一个带有分隔符 ( \
) 分隔字符串的单元格。这个字符串的一个例子是:
category_path
=============
RootCategory\Middle Category\Child Category\Child of child category
RootCategory\Middle Category\Other Child Category\
Run Code Online (Sandbox Code Playgroud)
有很多这样的类别路径。我想将它们全部解析到另一个表中:
category_name parent_path
====================================
RootCategory null
Middle Category RootCategory
Child Category RootCategory\Middle Category
Child of child category RootCategory\Middle Category\Child Category
Other Child Category RootCategory\Middle Category
Run Code Online (Sandbox Code Playgroud)
我在这里省略了重复项,但结果可能包含重复项(稍后我需要将光标移到该表的行上,我可以在那里调用 distinct )。
网络上有很多字符串被简单分割的例子。(例如此处)我正在考虑编写一个查询,在其中拆分字符串,将光标移到结果上并在每一步中累积 parent_path,但这似乎非常不理想。
有没有一种解决方案,我不必为一个简单的字符串声明这么多游标?
用递归 CTE 拆分字符串通常是一个糟糕的选择,但在这种情况下,我至少会考虑使用它的解决方案。
如果您使用更快的字符串拆分技术,则必须保留项目的顺序并parent_category
使用for xml
. 这可能仍然比使用递归 CTE 更快,但无论如何这里是递归的东西。
MS SQL Server 2008 架构设置:
create table YourTable
(
category_path nvarchar(max)
);
insert into YourTable values
('RootCategory\Middle Category\Child Category\Child of child category'),
('RootCategory\Middle Category\Other Child Category\');
Run Code Online (Sandbox Code Playgroud)
查询 1:
with C as
(
select left(category_path, charindex('\', category_path+'\') - 1) as category_name,
stuff(category_path, 1, charindex('\', category_path+'\'), '') as category_path,
cast(null as nvarchar(max)) as parent_path
from YourTable
union all
select left(category_path, charindex('\', category_path+'\') - 1),
stuff(category_path, 1, charindex('\', category_path+'\'), ''),
coalesce(parent_path+'\', '')+category_name
from C
where category_path <> ''
)
select distinct
category_name,
parent_path
from C;
Run Code Online (Sandbox Code Playgroud)
结果:
| CATEGORY_NAME | PARENT_PATH |
-------------------------------------------------------------------------
| Child Category | RootCategory\Middle Category |
| Child of child category | RootCategory\Middle Category\Child Category |
| Middle Category | RootCategory |
| Other Child Category | RootCategory\Middle Category |
| RootCategory | (null) |
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
995 次 |
最近记录: |