表是
create table mtest
(
id int,
strval varchar(150),
strval1 varchar(150)
)
insert into mtest
values (1, 'a b c d', 'xxyyzzaa')
insert into mtest
values(2, 'e f', 'ccdd')
insert into mtest
values(3, 'g h i', 'llmmnn')
insert into mtest
values(4, 'j', 'kk')
答案应该是
1 xx
1 yy
1 zz
1 aa
2 cc
2 dd....
答案 0 :(得分:1)
试试这个
DECLARE @mtest TABLE (Id int, strval VARCHAR(150), strval1 VARCHAR(150))
INSERT INTO @mtest
VALUES
(1,'a b c d','xxyyzzaa'),
(2,'e f','ccdd'),
(3,'g h i','llmmnn'),
(4,'j','kk')
DECLARE @MaxLength INT = (SELECT MAX(LEN(strval1)) FROM @mtest)
;WITH CTE (RowId)
AS
(
SELECT 1 AS RowId
UNION ALL
SELECT RowId + 2 AS Id
FROM CTE
WHERE
RowId < @MaxLength
)
SELECT
M.Id,
M.strval1,
SUBSTRING(strval1, C.RowId, 2) AS Result
FROM
@mtest M CROSS JOIN
CTE C
WHERE
SUBSTRING(strval1, C.RowId, 2) != ''
ORDER BY M.Id
结果:
Id strval1 Result
------- ------------ ------
1 xxyyzzaa xx
1 xxyyzzaa yy
1 xxyyzzaa zz
1 xxyyzzaa aa
2 ccdd dd
2 ccdd cc
3 llmmnn ll
3 llmmnn mm
3 llmmnn nn
4 kk kk