的一种方法是使用递归CTE:
with keywords as (
select 1 as id, 'RENAULT CLIO MTV' as keywords union all
select 2 as id, 'A B' as keywords
),
cte as (
select id,
(case when keywords like '% %'
then left(keywords, charindex(' ', keywords))
else keywords
end) as keyword,
(case when keywords like '% %'
then substring(keywords, charindex(' ', keywords)+1, 1000)
else ''
end) as rest
from keywords
union all
select id,
(case when rest like '% %'
then left(rest, charindex(' ', rest))
else rest
end) as keyword,
(case when rest like '% %'
then substring(rest, charindex(' ', rest)+1, 1000)
else ''
end) as rest
from cte
where len(rest) > 0
)
select id, keyword
from cte;
使用相同的结构,你可以用insert
替换最终select
:
insert into KeywordSearches(name, keyword_id)
select keyword, id
from CTE;
这是假设您已将id
设置为标识列。
这是第一个查询的SQLFiddle。
编辑:
我认为最终的查询会是这样的:
with cte as (
select id,
(case when keywords like '% %'
then left(keywords, charindex(' ', keywords))
else keywords
end) as keyword,
(case when keywords like '% %'
then substring(keywords, charindex(' ', keywords)+1, 1000)
else ''
end) as rest
from keywords
union all
select id,
(case when rest like '% %'
then left(rest, charindex(' ', rest))
else rest
end) as keyword,
(case when rest like '% %'
then substring(rest, charindex(' ', rest)+1, 1000)
else ''
end) as rest
from cte
where len(rest) > 0
)
insert into KeywordSearches(name, keyword_id)
select keyword, id
from CTE;
您是否尝试过搜索网站在http://stackoverflow.com/questions/314824/t-sql-在这种情况下,您的分隔符将是空白区域,这与字符串拼接相反 - 如何将字符串拆分为多个字符串。 –
嗨,我没有找到我需要的匹配,因为如果我理解正确,他们分割一个字符串,而不是从表到另一个行。 – Patrick