2015-07-21 51 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很適合你,只需稍作調整即可。

有問題?