2011-05-02 93 views
1

我有問題,我有一個字符串,我需要得到它的特定部分。sql查詢字符之間的字

例如:

\Stack\Over\Programming\Users\ 

我需要從上面的字符串 「編程」。

回答

1
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 

結果:

CHARBegin |Res   |RN 
1   | \   |1 
7   |Stack  |2 
12   |Over  |3 
24   |Programming |4 
30   |Users  |5 

在你的情況,你需要的最後一條語句

SELECT * FROM res WHERE Rn=4 
1

如果它始終是這是第3和第4 \的話,以下將做三CK。

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) 
+0

@ Lieven..Thanks一個lot.This正是我想要的 – 2011-05-02 09:40:09

+0

@ramesh - 沒有提供問題,但解決Dalex具有更好的涼意因素。 – 2011-05-02 09:48:18

+1

也可以使用'PARSENAME(REPLACE(SUBSTRING(@ String,2,len(@String)-2),'','。'),2)'增加涼爽度(但不夠健壯!) – 2011-05-02 11:48:52