Reputation: 11
I have a Database that contains two columns, a date and then a column that is a sentence. Example: "2016-12-5" "I went out to the mall today". How can I split these columns of sentences into a single word per row while still keeping them connected to the correct date?
Upvotes: 0
Views: 242
Reputation: 6193
Use the split
function:
CREATE FUNCTION [dbo].[Split]
(@String VARCHAR (max), @Delimiter CHAR (1))
RETURNS
@temptable TABLE (
[items] VARCHAR (max) COLLATE SQL_Latin1_General_CP1_CI_AS NULL)
AS
begin
declare @idx int
declare @slice varchar(max)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
After creating the function, try this:
SELECT '2016-12-5' AS [Date],items Value FROM dbo.Split('I went out to the mall today',' ')
Upvotes: 1