user14544481
user14544481

Reputation: 13

Get a word from delimited a string

I am working on string of sentences and need to get specific sentence from the paragraph.

Example input ‘Tom is a cat. He loves playing outside. He also love eating.’

The separator is ‘.’, If I need the second sentence then: The result should be ‘He loves playing outside’

This should be done via ms sql scalar function.

Upvotes: 0

Views: 39

Answers (1)

dougp
dougp

Reputation: 3089

You'll need to adjust the data types and the search location (I don't know how many spaces and such you may have) to meet your needs, but here are the basics:

create function dbo.udf_SecondSentence (@s varchar(200))
returns varchar(200)
begin
    declare @n1 int
    , @n2 int

    set @n1 = CHARINDEX('.', @s)
    set @n2 = CHARINDEX('.', @s, CHARINDEX('.', @s) + 1)

    return SUBSTRING(@s, @n1 + 2, @n2 - @n1 - 2)
end
go


select dbo.udf_SecondSentence('Tom is a cat. He loves playing outside. He also love eating.')

Upvotes: 1

Related Questions