I have a column named Name in a table called test which has Full name and I am trying to extract First name and Last Name. So I wrote query something like this:
Declare @t table ( [Name] varchar(100) )
insert into @t ( Name )
VALUES ( 'dennis hopper' ), ('keanu reaves'), ('thatgirl')
SELECT
[Name],
CHARINDEX(' ', [Name]),
CASE WHEN CHARINDEX(' ', [Name]) > 0 THEN
LEFT([Name],CHARINDEX(' ',[Name])-1)
ELSE
[Name]
END as FIRST_NAME,
CASE WHEN CHARINDEX(' ', [Name]) > 0 THEN
SUBSTRING([Name],CHARINDEX(' ',[Name])+1, ( LEN([Name]) - CHARINDEX(' ',[Name])+1) )
ELSE
NULL
END as LAST_NAME
FROM @t