1

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

例子:

在表中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

我需要能够根据表关键字的每一行创建所有相关的关键字搜索。

谢谢。

4

1 回答 1

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;

使用相同的结构,您可以将 final 替换selectinsert

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;
于 2013-07-13T21:03:36.843 回答