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?

4

2 回答 2

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
于 2017-03-16T22:32:10.470 回答
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) <> ''; 
于 2017-03-16T22:16:19.807 回答