select 第三个和第四个竖线分隔符之间的字符串
select string between 3rd and 4th pipe delimiter
我有一列包含
等值
Column
Asset|Class1|Category1|Group1|Account1
Expense|Class23|Category23|Group23|Account23
我想 select 我的管道分隔符出现的第 3 次和第 4 次之间的字符串,我该如何实现?
我试过 PARSENAME 和 charindex+stuff 函数,但它们有限制,比如最多 128 个字符。此外,我们的 SQL 服务器对正则表达式的支持有限。有什么想法吗?
SELECT REVERSE(PARSENAME(REVERSE(replace(LTRIM(Column), '|', '.')), 3))
我的select需要return:
第一组
第 23 组
也许这会有所帮助
例子
Declare @YourTable table (ID int,[Column] varchar(max))
Insert Into @YourTable values
(1,'Asset|Class1|Category1|Group1|Account1')
,(2,'Expense|Class23|Category23|Group23|Account23')
Select ID
,SomeValue = convert(xml,'<x>' + replace([Column],'|','</x><x>')+'</x>').value('/x[3]','varchar(100)')
From @YourTable
Returns
ID SomeValue
1 Category1
2 Category23
你也可以用STRING_SPLIT()
如果你有2016+
CREATE TABLE T(
ID INT IDENTITY(1,1),
Str VARCHAR(45)
);
INSERT INTO T(Str) VALUES
('Asset|Class1|Category1|Group1|Account1'),
('Expense|Class23|Category23|Group23|Account23');
SELECT V Str
FROM (
SELECT Value V,
ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) RN
FROM T CROSS APPLY STRING_SPLIT(Str, '|')
) TT
WHERE RN = 3;
Returns:
Str
---------
Category1
Category23
我有一列包含
等值Column
Asset|Class1|Category1|Group1|Account1
Expense|Class23|Category23|Group23|Account23
我想 select 我的管道分隔符出现的第 3 次和第 4 次之间的字符串,我该如何实现?
我试过 PARSENAME 和 charindex+stuff 函数,但它们有限制,比如最多 128 个字符。此外,我们的 SQL 服务器对正则表达式的支持有限。有什么想法吗?
SELECT REVERSE(PARSENAME(REVERSE(replace(LTRIM(Column), '|', '.')), 3))
我的select需要return: 第一组 第 23 组
也许这会有所帮助
例子
Declare @YourTable table (ID int,[Column] varchar(max))
Insert Into @YourTable values
(1,'Asset|Class1|Category1|Group1|Account1')
,(2,'Expense|Class23|Category23|Group23|Account23')
Select ID
,SomeValue = convert(xml,'<x>' + replace([Column],'|','</x><x>')+'</x>').value('/x[3]','varchar(100)')
From @YourTable
Returns
ID SomeValue
1 Category1
2 Category23
你也可以用STRING_SPLIT()
如果你有2016+
CREATE TABLE T(
ID INT IDENTITY(1,1),
Str VARCHAR(45)
);
INSERT INTO T(Str) VALUES
('Asset|Class1|Category1|Group1|Account1'),
('Expense|Class23|Category23|Group23|Account23');
SELECT V Str
FROM (
SELECT Value V,
ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) RN
FROM T CROSS APPLY STRING_SPLIT(Str, '|')
) TT
WHERE RN = 3;
Returns:
Str
---------
Category1
Category23