Split string in T-SQL

2019-08-06 19:33发布

问题:

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

回答1:

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



回答2:

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.



回答3:

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.



回答4:

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?



回答5:

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



标签: tsql string