lets say i have a column Name in tableA
Name
jennifer Hughs
Mike nadrotosky
Arnold Woods
Raj Jai Soni
so how do i put these results in seperate 3 columns like
FirstName MiddleName LastName
Jennifer Hughs
.
.
.
Raj Jai Soni
I tried with Substring but not working.
Well, it looks at lot easier than it really is - especially if you start having people with multiple first- and/or middle names.
My approach would be to create a stored function that encapsulates that logic - it's really not that simple to just spell it out in an inline T-SQL statement.
Here's a first attempt - works as long as you don't have more than a single middle name:
CREATE FUNCTION dbo.SplitName(@InputName VARCHAR(200))
RETURNS @nameParts TABLE
(
FirstName VARCHAR(100),
MiddleName VARCHAR(100),
LastName VARCHAR(100)
)
AS BEGIN
DECLARE @FirstSpace INT, @LastSpace INT
SET @FirstSpace = CHARINDEX(' ', @InputName)
SET @LastSpace = CHARINDEX(' ', @InputName, @FirstSpace+1)
INSERT INTO @nameParts(FirstName, MiddleName, LastName)
SELECT
SUBSTRING(@InputName, 1, @FirstSpace),
CASE @LastSpace
WHEN 0 THEN CAST(NULL AS VARCHAR(100))
ELSE SUBSTRING(@InputName, @FirstSpace+1, @LastSpace - @FirstSpace)
END,
CASE @LastSpace
WHEN 0 THEN SUBSTRING(@InputName, @FirstSpace+1, 999)
ELSE SUBSTRING(@InputName, @LastSpace, 999)
END
RETURN
END
If you test this with some sample data, you'll get the following results:
DECLARE @nameTable TABLE (NameValue VARCHAR(100))
INSERT INTO @nametable VALUES('Jennifer Hughes')
INSERT INTO @nametable VALUES('Mike Nadrotosky')
INSERT INTO @nametable VALUES('Arnold Woods')
INSERT INTO @nametable VALUES('Raj Jai Soni')
SELECT *
FROM @nameTable
CROSS APPLY dbo.SplitName(nameValue)
and the output for that SELECT is:
NameValue FirstName MiddleName LastName
Jennifer Hughes Jennifer NULL Hughes
Mike Nadrotosky Mike NULL Nadrotosky
Arnold Woods Arnold NULL Woods
Raj Jai Soni Raj Jai Soni
@marc_s answer is the most complete. The few times I've had to do this they've been as one-off data load type jobs. If yours is the same I would strongly suggest just doing it in Excel!
For doing this in T-SQL I have done it using the string split function in SQL Sharp . This will however ultimately yield similar results to @marc_s so I won't go in to it here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.