sql更改位置

p4rjhz4m  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(423)

我有一个这样的领域

username
Vo, Tony (12322)
Beaty, Nancy (34343)

我想把前面的名字改成这样

username
Tony Vo (12322)
Nancy Beaty (34343)
ssgvzors

ssgvzors1#

如果您的示例数据具有代表性并且与实际数据一致,您可以尝试使用parsename。

select trim(parsename(name,2) + 
            parsename(name,3) + ' (' + 
            parsename(name,1)) as new_name
from your_table t1
cross apply (select translate(username,',(','..') as name) t2;

也可以使用子查询或 CTE 而不是 cross apply ```
with cte as
(select translate(username,',(','..') as username
from your_table)

select trim(parsename (username,2) +
parsename (username,3) + ' (' +
parsename (username,1))
from cte;

h79rfbju

h79rfbju2#

DECLARE @CoolTable AS TABLE (id int PRIMARY KEY IDENTITY(1,1), [name] nvarchar(100))
INSERT INTO @CoolTable values
    ('Man, Jo (123546)'),
    ('Vo, Tony (5533)'),
    ('Beaty, Nancy (7766)'),
    (',badData1 (100)'),
    ('badData2 (101)'),
    (',badData3')

SELECT
    CASE WHEN CHARINDEX(',', [name]) > 0 AND CHARINDEX('(', [name]) > 0 THEN
        RTRIM(LTRIM(SUBSTRING([name], CHARINDEX(',', [name])+1, CHARINDEX('(', [name]) - CHARINDEX(',', [name]) - 1)))
        + ' '
        + SUBSTRING([name], 0, CHARINDEX(',', [name]))
        + ' '
        + LTRIM(SUBSTRING([name], CHARINDEX('(', [name]) - 1, 100))
    ELSE
        [name]
    END AS [NewName]
FROM @CoolTable

输出:

NewName
---------------------------
Jo Man (123546)
Tony Vo (5533)
Nancy Beaty (7766)
badData1  (100)
badData2 (101)
,badData3

这个密码不能给我带来快乐。按照marie kondo的说法,我应该把它去掉。如果由我决定,我会看看如何改进原始数据插入的过程(例如,获取3个不同的字段)。

相关问题