繁体   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