关于SQL SERVER 数据拆分

来源:互联网 发布:俄罗斯 奥运会 知乎 编辑:程序博客网 时间:2024/06/05 08:39

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