if object_id('tb') is not null drop table tb
go
create table tb([A] varchar(10),[B] int)
insert tb
select 'bcd',1 union all
select 'bcde',2 union all
select 'cd',3
go
個人分析這道題的思路是:
通過Substring() 來循環分割 B 列下的字符串。。
--想得到的結果:
/**
a b
---- -----------
b 1
c 1
d 1
b 2
c 2
d 2
e 2
c 3
d 3
(所影響的行數爲 9 行)
**/
(1):select
substring(a.A,b.number,1) as a,a.b
from tb a,
master..spt_values b
where b.type='P' and b.number>0
and b.number<len(a.a)
/**
a b
---- -----------
b 1
c 1
d 1
b 2
c 2
d 2
e 2
c 3
d 3
(所影響的行數爲 9 行)
**/
(2)
SELECT TOP 100 ID=IDENTITY(INT,1,1) INTO #NUM FROM SYS.SYSCOLUMNS A,SYS.SYSCOLUMNS B
SELECT
A.b,[VALUE]=SUBSTRING(A.a,B.ID,1)
FROM
#TB A,#NUM B
WHERE
b.id <=len(a.a)
/*
b VALUE
----------- -----
1 b
1 c
1 d
2 b
2 c
2 d
2 e
3 c
3 d