简体   繁体   English

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

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

Using T-SQL, I'm trying to find the easiest way to make "Test One" become "One, Test" . 使用T-SQL,我试图找到使"Test One"成为"One, Test"的最简单方法。

Basically switch the " " and ", " if there are just 2 words in a column with a space between them. 如果一列中只有2个单词,并且它们之间有空格,则基本上切换“”和“,”。

For example: 例如:

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

How about this: 这个怎么样:

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

See SQL Fiddle with Demo . 请参阅带有演示的SQL Fiddle The result is: 结果是:

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

SQL Fiddle 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

Here is my take : Not the best as it uses quiet a number of string functions... 这是我的观点:不是最好的,因为它使用许多字符串函数来静音...

  • Assumptions: 假设:

    1. That you only have two words ;) 你只有两个字;)

    2. There is a space/ or ther character... 有一个空格/或另一个字符...

  • SQLFIDDLE DEMO SQLFIDDLE演示

Code: 码:

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;

Results: 结果:

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

ps: I used an old table in sql server for the demo.. ps:我在sql server中使用了一个旧表进行演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM