Finding a space in T-SQL

G

Guest

Hello,

If I have a string "Mr. Bill Gates" stored as an nvarchar variable how would I split it into two strings "Mr. Bill" and "Gates" using T-SQL? I assume I could use Substring but to use that I would have to know the index of the last whitespace and don't know how to get that index. Any suggestions would be appreciated. Thanks!
 
G

Guest

Hi
Here is a quick fix. There could be a better way.

declare @v varchar(50)
select @v='Mr. Bill Gates'

select ltrim(reverse(substring(reverse(@v),1,charindex(' ',reverse(@v)))))
 
M

Mark Rae

Solel Software said:
Hello,

If I have a string "Mr. Bill Gates" stored as an nvarchar variable how
would I split it into two strings "Mr. Bill" and "Gates" using T-SQL? I
assume I could use Substring but to use that I would have to know the index
of the last whitespace and don't know how to get that index. Any
suggestions would be appreciated. Thanks!

DECLARE @strInput varchar(50)
SELECT @strInput = 'Mr. Bill Gates'

SELECT LEFT(@strInput, CHARINDEX(' ', @strInput) - 1) AS LeftSide
SELECT SUBSTRING(@strInput, CHARINDEX(' ', @strInput) + 1,
DATALENGTH(@strInput) - CHARINDEX(' ', @strInput)) AS RightSide
 
G

Guest

Thank you so much Ibrahim! This works great.


Ibrahim Shameeque said:
Hi
Here is a quick fix. There could be a better way.

declare @v varchar(50)
select @v='Mr. Bill Gates'

select ltrim(reverse(substring(reverse(@v),1,charindex(' ',reverse(@v)))))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,185
Latest member
GluceaReviews

Latest Threads

Top