views:

703

answers:

5

How can I get the string "text." from the string "This is my text."?

+6  A: 

SELECT RIGHT('This is my text.',5)

KM
A: 

Is this a specific example of some more general problem? @KM's answer is glib but I was going to say

SELECT 'text'

I'm guessing you're after something else?

n8wrl
In your answer, it would be SELECT 'text.' However, OP said it was part of the larger string "This is my text.", hence the RIGHT().
KM
+5  A: 

SELECT SUBSTRING('This is my text.',CHARINDEX('text.','This is my text.'),5)

Right() will fail if "text." will be in middle of the string.

Rajesh
you can list 1,000 _possible_ issues, however, there are only two facts to this question: the given string and what the result should be. based on that "text." will never be in the middle of the string.
KM
The given string can be changed, what should be result is fact.
Rajesh
+1  A: 

I assume you would like to find "text." in any string literal or field in a table. Here's my approach (returning the original text to search, text to find, beginning position of the found text, and the extracted text):

declare @original varchar(1000), @find varchar(10)

set @original = 'This is my big string and I want to find the word "text" in it.'
set @find = 'text'

select  @original as original
     ,  @find as to_find
     ,  charindex(@original, @find) as start_position
     ,  substring(@original, charindex(@find, @original), len(@find)) as extract

Of course, substitute @original for the field in the table you're searching if applicable.

ACB
since you are adding assumptions to the question, you missed the one where @find is not in @original
KM
A: 

Without being unhelpful there is a link here that details this.

krystan honour