由于字符串始终具有固定长度,因此您可以这样做:
DECLARE @s VARCHAR(50) = '01AAAA02BBBB03CCCC';
SELECT *
FROM
(
SELECT SUBSTRING(@s, 01, 2) AS ID, SUBSTRING(@s, 3, 4) AS Name
UNION ALL
SELECT SUBSTRING(@s, 7, 2) AS ID, SUBSTRING(@s, 9, 4) AS Name
UNION ALL
SELECT SUBSTRING(@s, 13, 2) AS ID, SUBSTRING(@s, 15, 4) AS Name
) t;
这会给你:
ID Name
01 AAAA
02 BBBB
03 CCCC
更新:如果你想从表的列中获取这个字符串,你可以这样做:
DECLARE @t table(name varchar(50));
INSERT INTO @t VALUES
('01AAAA02BBBB03CCCC'),
('01DDDD02BBBB03CCCC'),
('01HHHH02QQQQ03CCCC'),
('01IIII02MMMM03CCCC');
SELECT *
FROM
(
SELECT SUBSTRING(name, 1, 2) AS ID, SUBSTRING(name, 3, 4) AS Name
FROM @t
UNION ALL
SELECT SUBSTRING(name, 7, 2) AS ID, SUBSTRING(name, 9, 4) AS Name
FROM @t
UNION ALL
SELECT SUBSTRING(name, 13, 2) AS ID, SUBSTRING(name, 15, 4) AS Name
FROM @t
) t;
这将为您提供以下信息:
ID Name
01 AAAA
01 DDDD
01 HHHH
01 IIII
02 BBBB
02 BBBB
02 QQQQ
02 MMMM
03 CCCC
03 CCCC
03 CCCC
03 CCCC