简体   繁体   English

从 A 列中提取子字符串并将其插入 B 列

[英]Extracting substring from Column A and inserting it into Column B

The values in Column A are formatted like the sample value below. A 列中的值的格式类似于下面的示例值。 I need to grab the value after the first dash (no space) and before the second dash (space on both sides).我需要在第一个破折号之后(无空格)和第二个破折号之前(两侧有空格)获取值。 If the target value can be captured simply by the spacing difference that will be fine.如果目标值可以简单地通过间距差异来捕获,那就没问题了。 Alternatively, the "CC" in the sample can have different values, but it is always 2 characters, so the beginning can also be identified as colon, space, 2 characters, dash (with no space).或者,样本中的“CC”可以有不同的值,但总是2个字符,所以开头也可以识别为冒号、空格、2个字符、破折号(没有空格)。

Sample Value:样本值:

John Doe: CC- Grab This Value - Some Other Random String - 01/16/2018

So in this example column B should be populated with Grab This Value所以在这个例子中,B 列应该填充Grab This Value

In SQL Server , you could use something like:SQL Server 中,您可以使用以下内容:

DECLARE @text varchar(100)='John Doe: CC-Grab This Value - Some Other Random String - 01/16/2018'

select @text as ColumnA,
       SUBSTRING(@text,
                 CHARINDEX('-',@text,1)+1,
                 CHARINDEX('-',@text,CHARINDEX('-',@text,1)+1)-CHARINDEX('-',@text,1)-1) as ColumnB

If this is SQL Server , you could use cross apply .如果这是SQL Server ,您可以使用cross apply I would include the space as part of the charindex just to be extra cautious, plus it's going to to simply the solution a little bit.我会将空间作为charindex一部分包含charindex只是为了更加谨慎,而且它会稍微简化解决方案。 The way this works is- you capture everything before the occurrence of - (with spaces around) and then capture everything after the first occurrence of - in the substring you just captured.它的工作方式是 - 您在-出现之前捕获所有内容(周围有空格),然后在您刚刚捕获的子字符串中第一次出现-之后捕获所有内容。

select col_a, col_b
from your_table
cross apply (select left(col_a, charindex(' - ', col_a)-1) as txt) t2
cross apply (select right(txt, charindex('-', reverse(txt))-2) as col_b) t3;

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM