SQL Server - 从字符串中获取子字符串

时间:2018-05-21 11:17:38

标签: sql sql-server

我有一个类似于'1234_XXXX_RHL_PQR'的字符串,在输出中我希望在'XXXX_' 'RHL'之后拉出字符。

我在字符串中总是'XXXX',我的任务是在'XXXX_'之后获取字符串

4 个答案:

答案 0 :(得分:1)

试试这个

DECLARE @Table AS TABLE (Data Nvarchar(100))
INSERT INTO @Table
SELECT '1234_XXXX_RHL_PQR'

SELECT Data,CAST('<S>'+REPLACE(Data,'_','</S><S>')+'</S>' AS XML).value('/S[3]','nvarchar(1000)') AS ReqData

FROM @Table

结果

Data                ReqData
----------------------------
1234_XXXX_RHL_PQR   RHL

DEMO:http://rextester.com/PXHSDZ80426

答案 1 :(得分:0)

尝试以下方法:

select 
right(yourfield,len(yourfield)-3-patindex('%XXXX%',yourfield))
from yourtable

答案 2 :(得分:0)

我会将substring()charindex()函数

一起使用
select col, substring(col, charindex('XXXX_', col)+5, len(col)) as Ncol
from table t;

答案 3 :(得分:0)

首先创建表值函数

CREATE FUNCTION [dbo].[Udf_GetReqString](@IputData Varchar(200))
RETURNS @OutTable TABLE
(
ActualData varchar(200),
ReqData varchar(200)
)
AS
BEGIN
    DECLARE @Table AS TABLE (Data Nvarchar(100))
    INSERT INTO @Table
    SELECT @IputData

    INSERT INTO @OutTable
    SELECT Data,SUBSTRING(DatReq,-1,CHARINDEX('_',Data )) AS DatReq
    FROM
    (
    SELECT Data,SUBSTRING(Data,CHARINDEX('X_',Data )+2,LEN(Data) )  AS DatReq
    FROM @Table
    )dt
RETURN
END

样本和呼叫功能

DECLARE @Table AS TABLE (Data Nvarchar(100))
INSERT INTO @Table
SELECT '1234_XXXX_SHL_PQR' UNION ALL
SELECT '1234_XXXX_RHL_PQR' UNION ALL
SELECT '1234_DDHDFD_XXXX_PHL_PQR' UNION ALL
SELECT '1234_ABAD_DADADA_XXXX_GHL_PQR'


SELECT t.Data,
        udf.ReqData 
FROM @Table t
CROSS APPLY [dbo].[Udf_GetReqString]  (t.Data) As udf

结果

Data                            ReqData
-------------------------------------------
1234_XXXX_SHL_PQR               SHL
1234_XXXX_RHL_PQR               RHL
1234_DDHDFD_XXXX_PHL_PQR        PHL
1234_ABAD_DADADA_XXXX_GHL_PQR   GHL

样本 http://sqlfiddle.com/#!18/2bcfa/1