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

时间:2013-01-14 19:28:38

标签: sql sql-server tsql

使用T-SQL,我正在尝试找到让"Test One"成为"One, Test"的最简单方法。

如果列中只有2个单词,并且它们之间有空格,则基本上切换“”和“,”。

例如:

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

3 个答案:

答案 0 :(得分:6)

这个怎么样:

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 with Demo。结果是:

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

答案 1 :(得分:2)

<强> SQL Fiddle

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

答案 2 :(得分:0)

这是我的看法:不是最好的,因为它使用了很多字符串函数......

  • 假设:

    1. 你只有两个字;)

    2. 有一个空格/或其他角色......

  • SQLFIDDLE DEMO

代码:

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中使用旧表进行演示..