使用 SQL 从字符串中提取 ID
Extract Id's from String with SQL
我想通过 SQL(无 T-SQL)
从以下字符串中提取 ID
XY_FOO_BAR1=123;XY_FOO_BAR2=456;XY_FOO_BAR3=789;
结果应如下所示:
123
456
789
使用 T-SQL 会很容易,但是我怎样才能解决纯 SQL 的问题呢?我已经用 PATINDEX
、CHARINDEX
和 SUBSTRING
尝试了一些东西,但不幸的是,这很复杂,当然更容易实现。
如有任何提示,我将不胜感激。
最终解决方案感谢@mtdot:
with List as (
select v.value as keyValue
from xy.foo cross apply STRING_SPLIT(stay_val,';') as v
where id = 987654321
)
select (select value from STRING_SPLIT(KeyValue, '=') order by value desc offset 1 rows fetch next 1 rows only) as Ids from List
试过这个似乎没问题。
但是 order by value
似乎很棘手
declare @Raw nvarchar(max) = 'XY_FOO_BAR1=123;XY_FOO_BAR2=456;XY_FOO_BAR3=789;';
with List as (
select value as KeyValue from STRING_SPLIT(@Raw, ';') where value != ''
)
select (select value from STRING_SPLIT(KeyValue, '=') order by value desc offset 1 rows fetch next 1 rows only) as Ids from List
希望这会有所帮助
=======
declare @a varchar(100);
set @a = 'XY_FOO_BAR1=123;XY_FOO_BAR2=456;XY_FOO_BAR3=789;';
;with split1(whole) as
(
select value from string_split(@a,';') where value <> ''
)
SELECT (select value from String_split(whole, '=') order by value desc offset 1 rows) FROM split1
我想通过 SQL(无 T-SQL)
从以下字符串中提取 IDXY_FOO_BAR1=123;XY_FOO_BAR2=456;XY_FOO_BAR3=789;
结果应如下所示:
123
456
789
使用 T-SQL 会很容易,但是我怎样才能解决纯 SQL 的问题呢?我已经用 PATINDEX
、CHARINDEX
和 SUBSTRING
尝试了一些东西,但不幸的是,这很复杂,当然更容易实现。
如有任何提示,我将不胜感激。
最终解决方案感谢@mtdot:
with List as (
select v.value as keyValue
from xy.foo cross apply STRING_SPLIT(stay_val,';') as v
where id = 987654321
)
select (select value from STRING_SPLIT(KeyValue, '=') order by value desc offset 1 rows fetch next 1 rows only) as Ids from List
试过这个似乎没问题。
但是 order by value
似乎很棘手
declare @Raw nvarchar(max) = 'XY_FOO_BAR1=123;XY_FOO_BAR2=456;XY_FOO_BAR3=789;';
with List as (
select value as KeyValue from STRING_SPLIT(@Raw, ';') where value != ''
)
select (select value from STRING_SPLIT(KeyValue, '=') order by value desc offset 1 rows fetch next 1 rows only) as Ids from List
希望这会有所帮助
=======
declare @a varchar(100);
set @a = 'XY_FOO_BAR1=123;XY_FOO_BAR2=456;XY_FOO_BAR3=789;';
;with split1(whole) as
(
select value from string_split(@a,';') where value <> ''
)
SELECT (select value from String_split(whole, '=') order by value desc offset 1 rows) FROM split1