简体   繁体   English

SQL子字符串charindex

[英]SQL substring charindex

I have a SQL field with a string like this 我有一个像这样的字符串的SQL字段

27/08/2018 to 31/08/2018 - GCH/10561/201312361J/HO
04/09/2018 to 07/09/2018 - GCH/2836/202788279H/WAL

This string has a reference code I need to extract. 该字符串具有我需要提取的参考代码。 The one bolded above. 上面加粗的一个。

The problem is the string before it has not always the same length. 问题是之前的字符串长度并不总是相同。 See second example above. 请参阅上面的第二个示例。

How can I extract that code each time? 如何每次都提取该代码?

Ive tried this, but i need to the left of the last "/"..... 我已经尝试过了,但是我需要在最后一个“ /”的左侧.....

SELECT Right('27/08/2018 to 31/08/2018 - GCH/10561/201312361J/HO', CHARINDEX('/','27/08/2018 to 31/08/2018 - GCH/10561/201312361J/HO')-1)

I think I need to use a substring and charindex but cannot get it working. 我想我需要使用一个substringcharindex但无法正常工作。

Thanks in advance for your help. 在此先感谢您的帮助。

This will locate the wanted string, but it requires quite a deal of reversing to get there. 这将找到所需的字符串,但是需要相当多的反转才能到达该字符串。 I have used a cross apply but you don't have to. 我使用了交叉申请,但您不必这样做。

CREATE TABLE test(
   column_a VARCHAR(50) NOT NULL PRIMARY KEY
);
INSERT INTO test(column_a) VALUES ('27/08/2018 to 31/08/2018 - GCH/10561/201312361J/HO');
INSERT INTO test(column_a) VALUES ('04/09/2018 to 07/09/2018 - GCH/2836/202788279H/WAL');


select
      column_a, ca.x
from test
cross apply (
    select reverse(substring(reverse(column_a),CHARINDEX('/',reverse(column_a))+1,10))
    ) ca (x)

You can try below 您可以在下面尝试

DEMO DEMO

declare @text varchar(64)
set @text='27/08/2018 to 31/08/2018 - GCH/10561/201312361J/HO'
select reverse(substring(reverse(right(@text,CHARINDEX('-',@text)-3)),CHARINDEX('/',reverse(right(@text,CHARINDEX('-',@text)-3)))+1,10))

OUTPUT: OUTPUT:

val
201312361J

This is assuming MS SQL Server: 这是假设MS SQL Server:

declare @rev varchar(64)
set @rev=reverse('27/08/2018 to 31/08/2018 - GCH/10561/201312361J/HO')
SELECT 
reverse(SUBSTRING ( @rev,  charindex('/', @rev) + 1, charindex('/', substring(@rev, (charindex('/', @rev) + 1) + 1, Len(@rev)))));

Explanation: 说明:

  • First we reverse the original string using reverse. 首先,我们使用反向反转原始字符串。
  • Then we find the substring between the first occurrence of '/' and the next occurrence of '/' 然后我们找到第一个出现的“ /”和下一个出现的“ /”之间的子字符串
  • We reverse the string again to find our original string. 我们再次反转字符串以找到原始字符串。

Assuming Postgres and that the - always precedes the second group of information: 假设Postgres并且-始终位于第二组信息之前:

with test(data) as (
values 
  ('27/08/2018 to 31/08/2018 - GCH/10561/201312361J/HO'), 
  ('04/09/2018 to 07/09/2018 - GCH/2836/202788279H/WAL')
)
select split_part(split_part(data, '-', 2), '/', 3)
from test;

returns: 收益:

split_part
----------
201312361J
202788279H

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

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