从特定位置的字符串中获取值
Get value from string in specific place
我正在使用 T-SQL 语言,我想知道从字符串中获取特定信息的最佳方法。
字符串示例:
Category : azd Nom du fichier : 684157 Type de doc : info Id : 21542
我们的想法是获取值“684157”,它将始终介于 "fichier :" 和 "Type" 之间。
我试过 substring
和 charindex
但我错过了一些东西。
这是我的代码
select substring(com, charindex('fichier : ', com)+len('fichier : '), charindex('Type', com)-charindex('fichier : ', com) + len('Type'))
from myTable
可能有更简洁的方法,但这里有一个使用 CHARINDEX
和 SUBSTRING
的方法。
SELECT SUBSTRING(com,
CHARINDEX('fichier :', com) + LEN('fichier :'), -- start index
CHARINDEX('Type :', com) - (CHARINDEX('fichier :', com) + LEN('fichier :'))) -- length
FROM MyTable
startIndex
是fichier :
的索引加上fichier :
的长度。结束索引是Type :
的索引。对于 SUBSTRING
我们需要使用起始索引和长度。为了计算子字符串的长度,我们使用 Type :
的索引并减去我们为 startIndex
.
计算的内容
这就是我要做的:
SELECT LEFT(S.CutString,CHARINDEX(' Type :',S.CutString)) AS FinalString
FROM (VALUES('Category : azd Nom du fichier : 684157 Type : info Id : 21542'))V(String) --Would be your table
CROSS APPLY (VALUES(STUFF(V.String,1,CHARINDEX('fichier : ',V.String) + LEN('fichier : '),'')))S(CutString);
其他变体:
SELECT parsename(replace(replace(com,'fichier : ','.'), 'Type','.'),2)
FROM MyTable
测试:
我正在使用 T-SQL 语言,我想知道从字符串中获取特定信息的最佳方法。
字符串示例:
Category : azd Nom du fichier : 684157 Type de doc : info Id : 21542
我们的想法是获取值“684157”,它将始终介于 "fichier :" 和 "Type" 之间。
我试过 substring
和 charindex
但我错过了一些东西。
这是我的代码
select substring(com, charindex('fichier : ', com)+len('fichier : '), charindex('Type', com)-charindex('fichier : ', com) + len('Type'))
from myTable
可能有更简洁的方法,但这里有一个使用 CHARINDEX
和 SUBSTRING
的方法。
SELECT SUBSTRING(com,
CHARINDEX('fichier :', com) + LEN('fichier :'), -- start index
CHARINDEX('Type :', com) - (CHARINDEX('fichier :', com) + LEN('fichier :'))) -- length
FROM MyTable
startIndex
是fichier :
的索引加上fichier :
的长度。结束索引是Type :
的索引。对于 SUBSTRING
我们需要使用起始索引和长度。为了计算子字符串的长度,我们使用 Type :
的索引并减去我们为 startIndex
.
这就是我要做的:
SELECT LEFT(S.CutString,CHARINDEX(' Type :',S.CutString)) AS FinalString
FROM (VALUES('Category : azd Nom du fichier : 684157 Type : info Id : 21542'))V(String) --Would be your table
CROSS APPLY (VALUES(STUFF(V.String,1,CHARINDEX('fichier : ',V.String) + LEN('fichier : '),'')))S(CutString);
其他变体:
SELECT parsename(replace(replace(com,'fichier : ','.'), 'Type','.'),2)
FROM MyTable
测试: