读书人

这种SQL语句如何写

发布时间: 2013-03-12 11:19:35 作者: rapoo

这种SQL语句怎么写?
原来的表格式
单号 名称 唯一码
1 AAA 001|002|003
2 AAB 011|022|033
3 AAC 031|023|034

现在需要显示的效果
单号 名称 唯一码
1 AAA 001
1 AAA 002
1 AAA 003
2 AAB 011
2 AAB 022
2 AAB 033
3 AAC 023
3 AAC 031
3 AAC 034


[解决办法]


select 单号,名称,left(stuff('
[解决办法]
'+唯一码+'
[解决办法]
',1,number,''),charindex('
[解决办法]
',stuff('
[解决办法]
'+唯一码+'
[解决办法]
',1,number,''))-1) from tb,master..spt_values where type='p' and number <len(唯一码) and substring('
[解决办法]
'+唯一码+'
[解决办法]
',number,1)='
[解决办法]
'

[解决办法]

--测试数据
if not object_id('Tab') is null
drop table Tab
Go
Create table Tab([单号] int,[名称] nvarchar(50),[唯一码] nvarchar(50))
Insert Tab
select 1,N'AAA',N'001
[解决办法]
002
[解决办法]
003' union all
select 2,N'AAB',N'011
[解决办法]
022
[解决办法]
033' union all
select 3,N'AAC',N'031
------解决方案--------------------


023
[解决办法]
034'
Go

--用临时表的方法处理
if object_id('Tempdb..#Num') is not null
drop table #Num
go
select top 100 单号=Identity(int,1,1) into #Num from syscolumns a,syscolumns b
Select
a.单号,a.名称,唯一码=substring(a.唯一码,b.单号,charindex('
[解决办法]
',a.唯一码+'
[解决办法]
',b.单号)-b.单号)
from
Tab a,#Num b
where
charindex('
[解决办法]
','
[解决办法]
'+a.唯一码,b.单号)=b.单号

/*
结果:


单号 名称 唯一码
----------- --------- -----------
1 AAA 001
1 AAA 002
1 AAA 003
2 AAB 011
2 AAB 022
2 AAB 033
3 AAC 031
3 AAC 023
3 AAC 034

(所影响的行数为 9 行)


*/


[解决办法]

create table tbc(id int,mc varchar(10),wym varchar(50))

insert into tbc select 1,'AAA','001
[解决办法]
002
[解决办法]
003'
union all
select 2,'AAB','011
[解决办法]
022
[解决办法]
033'
union all
select 3,'AAC','031
[解决办法]
023
[解决办法]
034'


declare @id int
declare @t table (id int,mc varchar(200),wym varchar(200))
declare my_cur cursor for select id from tbc
open my_cur

fetch next from my_cur into @id

while @@fetch_status=0
begin

declare @wym varchar(30),@sq1 varchar(1000)
set @wym=(select wym from tbc where id=@id)

while len(@wym)>0


begin
set @sq1=substring(@wym,1,case patindex('%
[解决办法]
%',@wym) when 0 then 200 else patindex('%
[解决办法]
%',@wym)-1 end )
insert into @t select id,mc,@sq1 from tbc where id=@id
set @wym=substring(@wym,case patindex('%
[解决办法]
%',@wym) when 0 then 500 else patindex('%
[解决办法]
%',@wym)+1 end ,2000)
end

fetch next from my_cur into @id


end
close my_cur
deallocate my_cur
select * from @t

读书人网 >SQL Server

热点推荐