的一種方法是使用遞歸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