I have a table
Create Table Keywords (keyword nvarchar(100))
I would like to split all of my email subjects and insert them into my Keywords table.
This is an email
The cats and Dogs mailing
I want each word to return as rows.
I have a table
Create Table Keywords (keyword nvarchar(100))
I would like to split all of my email subjects and insert them into my Keywords table.
This is an email
The cats and Dogs mailing
I want each word to return as rows.
You can use a function like this one:
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
And select with this
select *
from dbo.fnSplit('This is an email
The cats and Dogs mailing',' ')
Here's a different approach. It looks stranger, but it can actually perform faster than substringing.
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
Firstly you might want to avoid putting in duplicates and get unique words in there or add a column and update the counter to know how many times the word had appeared in a subject line.
This solution could very well work for you with a little tweak.
Questions?