0

I'm a SQL acolyte, spending most of my time in Powershell. So for the purposes of this, I shall express myself thusly. Basically, I have a column of FullName, that contains FirstName LastName, and I want it restructured to LastName, Firstname in a SELECT query.

If I wasn't clear enough, in Powershell I would do this:

$string = "John Smith"
$split = $string.Split(' ')
$builder = "$($split[0]), $($split[1])"

How does one accomplish this in SQL?

user3066571
  • 1,381
  • 4
  • 14
  • 37

2 Answers2

1

As your data is nice and consistent, you can use a combination of the CHARINDEX and SUBSTRING functions:

SELECT
    SUBSTRING(FullName, 0, CHARINDEX(' ', FullName)) AS FirstName,
    SUBSTRING(FullName, CHARINDEX(' ', FullName)+1, LEN(FullName)) AS LastName
FROM NamesTable

Now if you want to join them back together, just use some string concatentation:

SELECT
    SUBSTRING(FullName, CHARINDEX(' ', FullName)+1, LEN(FullName))
    + ', ' +
    SUBSTRING(FullName, 0, CHARINDEX(' ', FullName))
FROM NamesTable
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • Would that not separate them into two columns? How would I combine them into one, separated by a comma and space? – user3066571 Mar 17 '17 at 15:23
  • 1
    Yes, but I thought it would be fairly obvious how to concatenate them together again - I've added the code for that. – DavidG Mar 17 '17 at 15:25
0

Sql Server 2016. https://msdn.microsoft.com/en-us/library/mt684588.aspx

DECLARE @tags NVARCHAR(400) = 'clothing,road,,touring,bike'  

SELECT value  
FROM STRING_SPLIT(@tags, ',')  
WHERE RTRIM(value) <> ''; 
DavidG
  • 113,891
  • 12
  • 217
  • 223