例子如下:
create table test(name varchar(20),num varchar(20))
insert test
select 'aa','5/6/9' union all
select 'bb','6/7/8'
go
--drop table test
select
a.name[col2],col1=substring(a.num,b.number,charindex('/',a.num+'/',b.number)-b.number)
from
test a join master..spt_values b
ON B.type='p' AND B.number BETWEEN 1 AND LEN(A.num)
where
substring('/'+a.num,b.number,1)='/'
order by col1
col2 col1
-------------------- --------------------
aa 5
aa 6
bb 6
bb 7
bb 8
aa 9
(所影响的行数为 6 行)
2005方法:
----------------------------------------------------------------
-- Author :fredrickhu(我是小F,向高手学习)
-- Date :2009-09-08 16:19:47
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([name] varchar(2),[num] varchar(20))
insert [tb]
select 'aa','5/6/9' union all
select 'bb','6/7/8'
--------------开始查询--------------------------
SELECT A.name, B.num
FROM(
SELECT name, [num] = CONVERT(xml,' <root> <v>' + REPLACE([num], '/', ' </v> <v>') + ' </v> </root>') FROM tb
)A
OUTER APPLY(
SELECT num = N.v.value('.', 'varchar(100)') FROM A.[num].nodes('/root/v') N(v)
)B
----------------结果----------------------------
/* name num
---- ----------------------------------------------------------------------------------------------------
aa 5
aa 6
aa 9
bb 6
bb 7
bb 8
(6 行受影响)
*/