The problem with your source code is here:
CHARINDEX(' ',[Name])-1
If [Name] does not contain a space, CharIndex returns 0. You subtract 1 and pass this to the left function. When the second parameter on the left is -1, you will get this error. In my opinion, the easiest way to โfixโ this problem is to let the CharIndex function find something:
CHARINDEX(' ',[Name] + ' ')-1
Now ... this code cannot fail.
You only NEED to make this one place in the source code, but you should also add it to the LAST_NAME part. If you do not, you will get incorrect results (although you will not get an error).
SELECT [Name], LEFT([Name],CHARINDEX(' ',[Name] + ' ')-1) AS FIRST_NAME, SUBSTRING([Name],CHARINDEX(' ',[Name] + ' ')+1,LEN([Name])) AS LAST_NAME FROM Test
This query will return the same results as the query suggested by @Sage, but (in my opinion) it is easier to read and easier to understand.
G mastros
source share