获取关键字列表的一种方法是使用递归 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;
使用相同的结构,您可以将 final 替换select
为insert
:
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;