sql query to get word between characters
I have problem where I have a string and I need to get a specific part of it.
For example:
\Stack\Over\Programmi开发者_StackOverflowng\Users\
I need "Programming" from the above string.
DECLARE @TExt NVARCHAR(MAX)= '\Stack\Over\Programming\Users\'
DECLARE @Delimiter VARCHAR(1000)= '\' ;
WITH numbers
AS ( SELECT ROW_NUMBER() OVER ( ORDER BY o.object_id, o2.object_id ) Number
FROM sys.objects o
CROSS JOIN sys.objects o2
),
c AS ( SELECT Number CHARBegin ,
ROW_NUMBER() OVER ( ORDER BY number ) RN
FROM numbers
WHERE SUBSTRING(@text, Number, LEN(@Delimiter)) = @Delimiter
),
res
AS ( SELECT CHARBegin ,
CAST(LEFT(@text, charbegin) AS NVARCHAR(MAX)) Res ,
RN
FROM c
WHERE rn = 1
UNION ALL
SELECT c.CHARBegin ,
CAST(SUBSTRING(@text, res.CHARBegin+1,
c.CHARBegin - res.CHARBegin-1) AS NVARCHAR(MAX)) ,
c.RN
FROM c
JOIN res ON c.RN = res.RN + 1
)
SELECT *
FROM res
Result:
CHARBegin |Res |RN
1 | \ |1
7 |Stack |2
12 |Over |3
24 |Programming |4
30 |Users |5
In your case you need last statement
SELECT * FROM res WHERE Rn=4
If it is always the word between the 3th and 4th \
, following would do the trick.
DECLARE @String VARCHAR(32)
SET @String = '\Stack\Over\Programming\Users\'
SELECT SUBSTRING(
@String
, CHARINDEX('\', @String, CHARINDEX('\', @String, CHARINDEX('\', @String, 1) + 1) + 1) + 1
, CHARINDEX('\', @String, CHARINDEX('\', @String, CHARINDEX('\', @String, CHARINDEX('\', @String, 1) + 1) + 1) + 1)
- CHARINDEX('\', @String, CHARINDEX('\', @String, CHARINDEX('\', @String, 1) + 1) + 1) - 1)
you will need to create a string split function in SQL. unfortunately there is not one built into MS SQL.
How do I split a string so I can access item x?
精彩评论