I have a column in a table that looks like this
Name |
---|
WALKER^JAMES^K^^ |
ANDERSON^MICHAEL^R^^ |
HUFF^CHRIS^^^ |
WALKER^JAMES^K^^ |
SWEARINGEN^TOMMY^L^^ |
SMITH^JOHN^JACCOB^^ |
I need to write a query that looks like this
Name | FirstName | LastName | MiddleName |
---|---|---|---|
WALKER^JAMES^K^^ | JAMES | WALKER | K |
ANDERSON^MICHAEL^R^^ | MICHAEL | ANDERSON | R |
HUFF^CHRIS^^^ | CHRIS | HUFF | |
BUTLER^STEWART^M^^ | STEWART | BUTLER | M |
SWEARINGEN^TOMMY^L^^ | TOMMY | SWEARINGEN | L |
SMITH^JOHN^JACCOB^^ | JOHN | SMITH | JACCOB |
I need help generating the LastName column.
This is what I've tried so far
SUBSTRING
(
--SEARCH THE NAME COLUMN
Name,
--Starting after the first '^'
CHARINDEX('^', Name) + 1 ),
--Index of second ^ minus the index of the first ^
(CHARINDEX('^', PatientName, CHARINDEX('^', PatientName) +1)) - (CHARINDEX('^', PatientName))
)
This produces:
Invalid length parameter passed to the LEFT or SUBSTRING function.
I know this can work because if I change the minus sign to a plus sign it performs as expected. It produces the right integer.
Where am I going wrong? Is there a better way to do this?