2016-08-10 57 views
0

我發現下面的查詢對我正在處理的應用程序非常有用。但是,我想替換表中某個選擇的值。如何使用SQL Server 2008中的select進行反向和拆分?

WITH data AS 
(
    select Value, REVERSE(Value) AS ReverseValue from (values 
     ('texttext/21/812/21a'), ('texttext/6/163/38a'), ('texttext/53/7a/a2'), ('text/t/e/xt/53/7a/a2') 
    )t(Value) 
), split AS 
(
    select 
     Value, ReverseValue, 
     reverse(substring(ReverseValue, 1, P1.Pos - 1)) AS Forth, 
     reverse(substring(ReverseValue, P1.Pos + 1, P2.Pos - P1.Pos - 1)) AS Third, 
     reverse(substring(ReverseValue, P2.Pos + 1, P3.Pos - P2.Pos - 1)) AS Second, 
     reverse(substring(ReverseValue, p3.Pos + 1, len(ReverseValue))) AS First 
    from data  
     cross apply (select (charindex('/', ReverseValue))) as P1(Pos) 
     cross apply (select (charindex('/', ReverseValue, P1.Pos+1))) as P2(Pos) 
     cross apply (select (charindex('/', ReverseValue, P2.Pos+1))) as P3(Pos) 
) 
select Value, First + '-' + Forth + Third + Second AS NewValue from split 

所以不是(values ('texttext/21/812/21a') (...)我想是這樣(select myfield from myutable)。任何想法如何做到這一點?謝謝。

回答

1

第一CTE只需更換值:

WITH data AS (
    select myfield, REVERSE(myfield) AS ReverseValue 
    from mytable 
    ), 
    . . .