T-SQL——将字符串转换为多列
志铭-2023年2月21日
0. 使用ParseName
- 注意:ParseName最多只能拆分为四列
- ParseName只能针对
.
,所以若是其他的分隔字符,需要先替换为.
WITH temp
AS (SELECT *
FROM
(
VALUES
('192.168.3.239'),
('192.168.3.232')
) AS T (IP) )
SELECT IP,
PARSENAME(IP, 1) AS IP1,
PARSENAME(IP, 2) AS IP2,
PARSENAME(IP, 3) AS IP3,
PARSENAME(IP, 4) AS IP4
FROM temp;
IP IP1 IP2 IP3 IP4
-------------- --- --- --- ---
192.168.3.239 239 3 168 192
192.168.3.232 232 3 168 192
1. 具体到拆分为两列
WITH temp
AS (SELECT *
FROM
(
VALUES
('1:2'),
('2:3')
) AS T (Ratio) )
SELECT Ratio,
LEFT(Ratio, CHARINDEX(':', Ratio) - 1) AS R1,
RIGHT(Ratio, (LEN(Ratio) - CHARINDEX(':', Ratio))) AS R2
FROM temp;
Ratio R1 R2
----- ---- ----
1:2 1 2
2:3 2 3
2. 具体到拆分的指定的列数
-- ======================================================
-- Author: shanzm
-- Create date: 2020年5月5日 17:01:40
-- Description: 将指定的字符串按照指定的分裂符分裂并返回指定
-- 位置的值
-- ======================================================
CREATE FUNCTION [dbo].[f_GetSplitByIndex]
(
@str VARCHAR(8000), --包含多个数据项的字符串
@index INT, --要获取的数据项的位置
@seprate VARCHAR(10) --数据分隔符
)
RETURNS VARCHAR(1000)
AS
BEGIN
IF @str IS NULL
RETURN (NULL);
DECLARE @splitlen INT;
SELECT @splitlen = LEN(@seprate + 'a') - 2;
WHILE @index > 1 AND CHARINDEX(@seprate, @str + @seprate) > 0
SELECT @index = @index - 1,
@str = STUFF(@str, 1, CHARINDEX(@seprate, @str + @seprate) + @splitlen, '');
RETURN (ISNULL(LEFT(@str, CHARINDEX(@seprate, @str + @seprate) - 1), ''));
END;
WITH temp
AS (SELECT '张三,李四,王五' AS A)
SELECT A,
dbo.f_GetSplitByIndex(A, 1, ',') AS A1,
dbo.f_GetSplitByIndex(A, 2, ',') AS A2,
dbo.f_GetSplitByIndex(A, 3, ',') AS A3
FROM temp;
--结果:
A A1 A2 A3
--------------- ------ ------ ------
张三,李四,王五 张三 李四 王五