2015-07-21 46 views
-3

我有一个表斯普利特场和插入的话到表

Create Table Keywords (keyword nvarchar(100)) 

我想拆我所有的电子邮件主题,并将其插入到我的关键词表。

This is an email 
The cats and Dogs mailing 

我希望每个单词都以行的形式返回。

+0

使用句子中的空格拆分电子邮件主题。 –

+0

是的,让每一个字是一个新的行 – PriceCheaperton

+0

你的问题是什么? –

回答

1

您可以使用函数像这样的:

CREATE FUNCTION [dbo].[fnSplit] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
     IF @end = 0 
      SET @end = LEN(@string) + 1 

     INSERT INTO @output (splitdata) 
     VALUES(SUBSTRING(@string, @start, @end - @start)) 
     SET @start = @end + 1 
     SET @end = CHARINDEX(@delimiter, @string, @start) 

    END 
    RETURN 
END 

而与此

select * 
from dbo.fnSplit('This is an email 
The cats and Dogs mailing',' ') 
1

选择这里有不同的方法。它看起来很陌生,但它实际上可以比子串更快地执行。

declare @string nvarchar(max) = 'This is an email' 
declare @xml xml 

-- Convert your string to an XML fragment 
set @xml = convert(xml, 
     '<tag keyword="' + replace(@string, ' ', '" /><tag keyword= "') + '" />'); 

-- Query your XML fragment for keyword nodes 
with Keywords as (
    select T.c.value('.', 'nvarchar(max)') as keyword 
    from @xml.nodes('/tag/@keyword') as T(c) 
) 
select * 
from Keywords 
where keyword > '' -- Remove blank entries caused by multiple spaces 
1

首先,你可能希望避免投入重复,并在那里获得独特的单词或添加一列更新计数器知道这个词曾多少次出现在主题行。

This solution很适合你,只需稍作调整即可。

有问题?