1

使用 T-SQL,我试图找到最简单的方法来制作"Test One"become "One, Test"

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

例如:

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

3 回答 3

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 |
于 2013-01-14T19:40:00.593 回答
2

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
于 2013-01-14T19:43:02.723 回答
0

这是我的看法:不是最好的,因为它使用了一些安静的字符串函数......

  • 假设:

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

于 2013-01-14T19:37:00.283 回答