仅当字符串大于特定长度时才将字符添加到字符串的特定位置

Add a character to a specific position of a string only if the string is > a particular length

我的平板电脑有一列数据如下所示:

A785
B21423
21432
031258A
358
Z94

我想添加一个'.'仅当原始字符串有 4 个或更多字符时才作为第 4 个字符,这将导致:

A78.5
B21.423
214.32
031.258A
358
Z94

我在 SQL 服务器管理工​​作室 18

中执行此操作

谢谢

请尝试以下解决方案。

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, token VARCHAR(30));
INSERT INTO @tbl (token) VALUES
('A785'),
('B21423'),
('21432'),
('031258A'),
('358'),
('Z94');
-- DDL and sample data population, end

SELECT *
    , IIF(size > 3, CONCAT(LEFT(token, 3), '.', RIGHT(token, size - 3))
        , token) AS tokenNew
FROM @tbl 
    CROSS APPLY (SELECT LEN(token)) AS t(size);

输出

+----+---------+------+----------+
| ID |  token  | size | tokenNew |
+----+---------+------+----------+
|  1 | A785    |    4 | A78.5    |
|  2 | B21423  |    6 | B21.423  |
|  3 | 21432   |    5 | 214.32   |
|  4 | 031258A |    7 | 031.258A |
|  5 | 358     |    3 | 358      |
|  6 | Z94     |    3 | Z94      |
+----+---------+------+----------+

我建议:

select (case when len(str) >= 4
             then stuff(str, 4, 0, '.')
             else str
        end)