[英]How to perform Split and Stringbuilding in SQL?
I'm a SQL acolyte, spending most of my time in Powershell. 我是一名SQL服务员,大部分时间都花在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. 基本上,我有一列FullName,其中包含
FirstName LastName
,并且我希望在SELECT
查询LastName, Firstname
其重组为LastName, Firstname
。
If I wasn't clear enough, in Powershell I would do this: 如果我不够清楚,可以在Powershell中执行以下操作:
$string = "John Smith"
$split = $string.Split(' ')
$builder = "$($split[0]), $($split[1])"
How does one accomplish this in SQL? 如何在SQL中做到这一点?
As your data is nice and consistent, you can use a combination of the CHARINDEX
and SUBSTRING
functions: 由于您的数据良好且一致,因此可以结合使用
CHARINDEX
和SUBSTRING
函数:
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
Sql Server 2016. https://msdn.microsoft.com/en-us/library/mt684588.aspx SQL Server 2016.https ://msdn.microsoft.com/zh-cn/library/mt684588.aspx
DECLARE @tags NVARCHAR(400) = 'clothing,road,,touring,bike'
SELECT value
FROM STRING_SPLIT(@tags, ',')
WHERE RTRIM(value) <> '';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.