2013-07-13 47 views
1

我需要创建一个查询,该查询从表中获取行,并将所有拆分字符串插入到相关表中。根据SQL Server中的字符串创建相关记录

例子:

在表Keywords我行:

Id Name 
1 RENAULT CLIO MTV 

,我需要创建一个查询,取行和这样的每个单词创建1行:

在表中KeywordSearches

Id: (Identity Increment) 
Name: RENAULT 
Keyword_Id: 1 

Id: (Identity Increment) 
Name: CLIO 
Keyword_Id: 1 

Id: (Identity Increment) 
Name: MTV 
Keyword_Id: 1 

I需要能够基于表关键字的每一行创建所有相关的关键字搜索。

谢谢。获得关键字列表

+1

您是否尝试过搜索网站在http://stackoverflow.com/questions/314824/t-sql-在这种情况下,您的分隔符将是空白区域,这与字符串拼接相反 - 如何将字符串拆分为多个字符串。 –

+0

嗨,我没有找到我需要的匹配,因为如果我理解正确,他们分割一个字符串,而不是从表到另一个行。 – Patrick

回答

4

的一种方法是使用递归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; 
+0

嗨,谢谢。我有困难去适应你的解决方案的关键字和KeywordSearches表,你能帮助吗?我无法找到将解决方案应用于关键字表格中所有行的方法。 – Patrick

+0

只需在'with'子句中删除'keywords'的定义即可。我把它放在那里只是为了测试目的。 –

+0

不好意思问,但你提到的什么改变适应了它? – Patrick

相关问题