SQL Server Extract data after 2nd last space up to 10 characters

cmssoen2  于 2023-06-21  发布在  其他
关注(0)|答案(3)|浏览(145)

How to extract data after 2nd last space up to 10 characters from a SQL Server column?

Column data is below:

INV PNI S000060803 1
INV PNI  P000035365 132
INV PRVC  S000059468 4
INV PIV P000034785 2
INV PIV  T000034785 27

Desired result is:

S000060803
P000035365
S000059468
P000034785
T000034785
kulphzqa

kulphzqa1#

You can use syntax working with all versions of SQL Server like this. It's a little bit messy, but should work on any version starting with 2005 at least. I'm using CTE just for demo to create virtual table.

with tmp as (
    select 'INV PNI S000060803 1' as c
    union all select 'INV PNI  P000035365 132'
    union all select 'INV PRVC  S000059468 4'
    union all select 'INV PIV P000034785 2'
    union all select 'INV PIV  T000034785 27'
)
select SUBSTRING(REVERSE(SUBSTRING(REVERSE(c), 0, CHARINDEX(' ', REVERSE(c), CHARINDEX(' ', REVERSE(c)) + 1))), 0, 11)
from tmp
qvtsj1bj

qvtsj1bj2#

Please try the following solution based on the PARSENAME() function use.

A minimal reproducible example is not provided. 😒

An assumption is made that the tokens column has just a single space character between words/tokens.

SQL #1

-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, tokens VARCHAR(256));
INSERT @tbl (tokens) VALUES
('INV PNI S000060803 1'),
('INV PNI P000035365 132'),
('INV PRVC S000059468 4'),
('INV PIV P000034785 2'),
('INV PIV T000034785 27');
-- DDL and sample data population, end

SELECT t.* 
    , PARSENAME(c, 2) AS result
FROM @tbl AS t
    CROSS APPLY (SELECT REPLACE(tokens, SPACE(1), '.')) AS t1(c);

SQL #2

Implementation when there are multiple spaces between words/tokens.

SELECT t.* 
    , PARSENAME(c, 2) AS result
FROM @tbl AS t
CROSS APPLY  (SELECT TRY_CAST('<r><![CDATA[' + tokens + ']]></r>' AS XML).value('(/r/text())[1] cast as xs:token?','VARCHAR(MAX)')) AS t1(x)
CROSS APPLY (SELECT REPLACE(x, SPACE(1), '.')) AS t2(c);

Output

idtokensresult
1INV PNI S000060803 1S000060803
2INV PNI P000035365 132P000035365
3INV PRVC S000059468 4S000059468
4INV PIV P000034785 2P000034785
5INV PIV T000034785 27T000034785
ddrv8njm

ddrv8njm3#

Late answer, but here is another option

Select A.ID
      ,NewVal = reverse(JSON_VALUE(JS,'$[1]'))
 From  YourTable A
Cross Apply (values ('["'+replace(string_escape(reverse( YourColumn ),'json'),' ','","')+'"]') ) B(JS)

相关问题