从列值STRING_SPLIT并在SQL Server中将其反转

时间:2018-01-01 13:06:57

标签: sql-server sql-server-2008

我正在尝试在SQL Server的列中反转字符串值。

我想要实现的是,当列的值为services: ... # makes classes in src/AppBundle/DataFixtures available to be used as services # and have a tag that allows actions to type-hint services AppBundle\DataFixtures\: resource: '../../src/AppBundle/DataFixtures' tags: ['doctrine.fixture.orm'] 时,我想在子项包含child/parent时将其更改为parent/child

例如,我想将值'112'的列更改为Reports/112-Major

首先,我尝试使用112-Major/Reports并将STRING_SPLIT添加为String_Split(ColumnName,'/')[1] + String_Split(ColumnName,'/')[0]

我在网上看到的

Most of the examples有类似

的内容
String_Split(ColumnName,'/')[1]  like '%112%'

但我想根据条件拆分然后合并,然后更新列

类似的东西,

SELECT Value FROM STRING_SPLIT('Lorem/ipsum/dolor/sit/amet.', '/');

有没有办法在SQL Server中执行此操作?

2 个答案:

答案 0 :(得分:3)

您可以使用以下表达式:

stuff(col, 1, charindex('/', col), '') + '/' + left(col, charindex('/', col) - 1)

答案 1 :(得分:2)

另一种选择只是为了好玩。

戈登的解决方案将是我的首选,当然更具性能(+1),但以下说明了一种简单的技术,可用于将字符串拆分为列而不是行。

<强>示例

Declare @YourTable table (ID int,YourCol varchar(100))
Insert Into @YourTable values
(1,'Reports/112-Major'),
(2,'Reports/Something Else')

Update @YourTable Set YourCol = Pos2+'/'+Pos1
 From  @YourTable A
 Cross Apply (
                Select Pos1 = ltrim(rtrim(xDim.value('/x[1]','varchar(max)')))
                      ,Pos2 = ltrim(rtrim(xDim.value('/x[2]','varchar(max)')))
                From  (Select Cast('<x>' + replace((Select replace(A.YourCol,'/','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) as xDim) as B1 
             ) B
 Where Pos2 Like '%112%'

更新结果

ID  YourCol
1   112-Major/Reports
2   Reports/Something Else