Get first name and last name from full name string in SQL 1

Get first name and last name from full name string in SQL

DECLARE @FullName    VARCHAR(50) = 'Mark Zuckerberg'

SELECT SUBSTRING(@FullName, 1, CHARINDEX(' ', @FullName) - 1) AS [First Name],
       SUBSTRING(@FullName, CHARINDEX(' ', @FullName) + 1, LEN(@FullName)) AS [Last Name]

Here is what the above code is Doing:
1. We declare a variable called @FullName and assign it the value ‘Mark Zuckerberg’.
2. We then use the SUBSTRING function to extract the first name.
3. We then use the SUBSTRING function to extract the last name.

The SUBSTRING function takes three parameters:
1. The string to extract from.
2. The starting position of the substring.
3. The length of the substring.

The CHARINDEX function takes two parameters:
1. The string to search for.
2. The string to search in.

The CHARINDEX function returns the starting position of the first occurrence of the string to search for.

The LEN function takes one parameter:
1. The string to return the length of.

The LEN function returns the length of the string.

The result of the above code is:

First Name Last Name
Mark Zuckerberg

Similar Posts