SQL SERVER – Puzzle – Get the First Name From Full Name Without CHARINDEX

This First Name From Full Name puzzle excludes CHARINDEX and SUBSTRING. It came from a customer query during a performance health check.

Four bead strands show distinct leading beads in widened receiving recesses.

DECLARE @Employee TABLE (ID int IDENTITY(1,1), Name varchar(100));
INSERT @Employee (Name) VALUES ('PINAL DAVE'), ('CHETAN DAVE'), ('BHIM RAO'), ('SRK SINGH');
SELECT ID, Name FROM @Employee ORDER BY ID;
-- Original baseline approaches, prohibited in the submitted answer:
SELECT LEFT(Name, CHARINDEX(' ', Name + ' ') - 1) AS FirstName FROM @Employee;
SELECT SUBSTRING(Name, 0, CHARINDEX(' ', Name, 0)) AS FirstName FROM @Employee;

The four required results are PINAL, CHETAN, BHIM and SRK. The baseline queries show the original requirement. Your submitted solution may use neither CHARINDEX nor SUBSTRING.

Explain a practical alternative and its assumptions. Multiple spaces, single-part names, Unicode and different naming structures need an explicit application requirement. The first space-delimited token isn’t universally a first name.

This example uses a table variable without creating a permanent database or overwriting an EMPLOYEE table. The challenge stays open for readers. The old Monday comment-release promise belonged to the original event.

Related reading

A first-token expression is not a universal name parser, it is a solution for explicitly stated input rules.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Function, SQL Scripts, SQL Server, SQL String
Previous Post
SQL SERVER – Puzzle – Strange Behavior With Extra Comma in Create Table Statement
Next Post
SQL SERVER – Puzzle – How Does Table Qualifier Work in INSERT Statement?

Related Posts

29 Comments. Leave new

  • declare @Name varchar(50)
    set @Name=’PINAL DAVE’
    select top 1 * from string_split( @Name , ‘ ‘)

    Reply
  • Sumit Salunkhe
    April 18, 2019 5:27 pm

    SELECT REPLACE(LEFT(REPLACE(Name,’ ‘,’$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$’) ,15),’$’,”) AS FirstName
    FROM EMPLOYEE

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.