简体   繁体   English

如何使用 SQL Substring 从此文件名中提取字符?

[英]How can I use SQL Substring to extract characters from this filename?

I'm attempting to use the SUBSTRING function to extract a name out of a filename.我正在尝试使用 SUBSTRING function 从文件名中提取名称。

An example filename would be: "73186_RHIMagnesita_PHI_StopLoss_TruncSSN_NonRedact_Inc_to_Apr2022_Paid_to_Apr2022_EDIT" I'm attempting to extract the "RHIMagnesita" from this filename.示例文件名是:“73186_RHIMagnesita_PHI_StopLoss_TruncSSN_NonRedact_Inc_to_Apr2022_Paid_to_Apr2022_EDIT” 我正在尝试从此文件名中提取“RHIMagnesita”。

The substring I used was:我使用的 substring 是:

SUBSTRING(DFH.FileName, CHARINDEX('_', DFH.FileName) + 1, CHARINDEX('_PHI', DFH.FileName) - 1)  

The results it gave were: "RHIMagnesita_PHI_S"它给出的结果是:“RHIMagnesita_PHI_S”

How do I extract only "RHIMagnesita" using the Substring function?如何使用 Substring function 仅提取“RHIMagnesita”?

The third parameter in SUBSTRING is length not position, so you would need to substract the length of the beginning string. SUBSTRING 中的第三个参数的长度不是 position,因此您需要减去开头字符串的长度。

SUBSTRING(DFH.FileName, CHARINDEX('_', DFH.FileName) + 1, CHARINDEX('_PHI', DFH.FileName) - CHARINDEX('_', DFH.FileName))

You might need to add or substract 1, but that's the idea.您可能需要加上或减去 1,但就是这样。

You were close.你很接近。 You need to use CHARINDEX to also find the position of the second underscore.您还需要使用CHARINDEX来查找第二个下划线的 position。

SELECT SUBSTRING(FileName,
                 CHARINDEX('_', FileName) + 1,
                 CHARINDEX('_', FileName, CHARINDEX('_', FileName) + 1) -
                     CHARINDEX('_', FileName) - 1) AS FilePart
FROM yourTable;

Here's a way using STRING_SPLIT and FETCH, rather than SUBSTRING We split the string and only return the second row这是使用 STRING_SPLIT 和 FETCH 的方法,而不是 SUBSTRING 我们拆分字符串并只返回第二行

SELECT
   value
FROM   STRING_SPLIT('73186_RHIMagnesita_PHI_StopLoss_TruncSSN_NonRedact_Inc_to_Apr2022_Paid_to_Apr2022_EDIT','_')
ORDER BY (SELECT NULL)
OFFSET 1 ROWS 
FETCH NEXT 1 ROWS ONLY;

Note: On Azure Sql Server STRING_SPLIT has an ordinal parameter, so you could write this注意:在 Azure Sql 服务器 STRING_SPLIT 上有一个序号参数,所以你可以这样写

SELECT
value
FROM
STRING_SPLIT('73186_RHIMagnesita_PHI_StopLoss_TruncSSN_NonRedact_Inc_to_Apr2022_Paid_to_Apr2022_EDIT','_', 1)
WHERE ordinal = 2

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

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