我有一个表A 数据结构为
id name
1 1|2
2 3|4|5
我想要结果为
id name
1 1
1 2
2 3
2 4
2 5
怎么写?
------解决方案--------------------
--drop table A
create table a(id int,name varchar(30))
insert into A
select 1, '1
------解决方案--------------------
2' union all
select 2, '3
------解决方案--------------------
4
------解决方案--------------------
5'
select id,
--a.name,
SUBSTRING(A.name, number ,CHARINDEX('
------解决方案--------------------
',a.name+'
------解决方案--------------------
',number)-number) as name
from A ,master..spt_values s
where s.number >=1
and s.type = 'P'
and SUBSTRING('
------解决方案--------------------
'+A.name,s.number,1) = '
------解决方案--------------------
'
/*
id name
1 1
1 2
2 3
2 4
2 5
*/
------解决方案--------------------
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-11-13 10:30:18
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([id] int,[name] varchar(5))
insert [A]
select 1,'1
------解决方案--------------------
2' union all
select 2,'3
------解决方案--------------------
4
------解决方案--------------------
5'
--------------开始查询--------------------------
select
id,
SUBSTRING(a.[name],number,CHARINDEX('
------解决方案--------------------
',a.[name]+'
------解决方案--------------------
',number)-number) as [name]
from
[A] a,master..spt_values
where
number >=1 and number<=len(a.[name])
and type='p'
and substring('
------解决方案--------------------
'+a.[name],number,1)='
------解决方案--------------------
'
----------------结果----------------------------
/*
id name
----------- -----
1 1
1 2
2 3
2 4
2 5
*/
------解决方案--------------------
create table t(id int,name varchar(30))
insert into t
select 1, '1
------解决方案--------------------
2' union all
select 2, '3
------解决方案--------------------
4
------解决方案--------------------
5'
with tb as
(
select id,name=cast( SUBSTRING(name+'
------解决方案--------------------
',1,charindex('
------解决方案--------------------
',name+'
------解决方案--------------------
')-1) as nvarchar(max))
,splitname=cast ( STUFF(name+'
------解决方案--------------------
',1,charindex('
------解决方案--------------------
',name+'
------解决方案--------------------
'),'') as nvarchar(max))
from t
union all
select id,cast (SUBSTRING(splitname,1,charindex('
------解决方案--------------------
',splitname)-1) as nvarchar(max))
,cast(STUFF(splitname,1,charindex('
------解决方案--------------------