簡體   English   中英

T-SQL:如何反轉字符串中的值

[英]T-SQL: How to reverse values in a string

使用T-SQL,我試圖找到使"Test One"成為"One, Test"的最簡單方法。

如果一列中只有2個單詞,並且它們之間有空格,則基本上切換“”和“,”。

例如:

Before             After
Test One           One, Test
Test Two One       Test Two One
Test, Three        Test, Three

這個怎么樣:

select col Before,
  case 
    when col like '%,%' then col 
    when len(replace(col, ' ', '')) = len(col) -1 
      then reverse(substring(reverse(col), 1, charindex(' ', reverse(col))-1))+', '+substring(col, 1, charindex(' ', col)-1)
    else col
  end  After
from yourtable

請參閱帶有演示的SQL Fiddle 結果是:

|       BEFORE |        AFTER |
-------------------------------
|     Test One |    One, Test |
| Test Two One | Test Two One |
|  Test, Three |  Test, Three |

SQL小提琴

DECLARE @Tests TABLE (
    Before VARCHAR(50)
)

INSERT INTO @Tests Values ('Test One')
INSERT INTO @Tests Values ('Test Two One')
INSERT INTO @Tests Values ('Test, Three')

SELECT
    Before,
    CASE 
        WHEN 
            -- If there is no comma...
            CHARINDEX(',', Before) = 0
            -- And if there is only one space... 
            AND CHARINDEX(' ', RIGHT(Before, LEN(Before) - 
                CHARINDEX(' ', Before))) = 0
        THEN 
            -- Then perform the swap.
            RIGHT(Before, LEN(Before) - CHARINDEX(' ', Before)) + ', ' 
            + LEFT(Before, CHARINDEX(' ', Before))
        -- Otherwise, retain the "before" value.
        ELSE Before
    END AS After
FROM @Tests

這是我的觀點:不是最好的,因為它使用許多字符串函數來靜音...

  • 假設:

    1. 你只有兩個字;)

    2. 有一個空格/或另一個字符...

  • SQLFIDDLE演示

碼:

SELECT CHARINDEX(' ',name) splitposition,
SUBSTRING(name, 1, CHARINDEX(' ',name)-1) firstword,
SUBSTRING(name, CHARINDEX(' ',name), len(name)) lastword,
(SUBSTRING(name, CHARINDEX(' ',name), len(name)) +
', ' + SUBSTRING(name, 1, CHARINDEX(' ',name)-1)) as swapped
from moneys;

結果:

| SPLITPOSITION | FIRSTWORD | LASTWORD |   SWAPPED |
----------------------------------------------------
|             5 |      test |      one |  one, test |

ps:我在sql server中使用了一個舊表進行演示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM