日期:2014-05-18  浏览次数:20428 次

使用SQL语句对字段值做解析
我有一张表table,有个字段   aa,   这个字段中值的表现形式是:     a,b,c,d,

我想把这个字段的值都解析成多条记录存放在另一张表里.如
1   a
2   b
3   c
4   d

应该如何写?

table这张表里有一万多条记录.

谢谢!!

------解决方案--------------------
select top 200 id=identity(int,1,1) into # from syscolumns a ,syscolumns b

select a=identity(int,1,1) substring(aa+ ', ',id,charindex( ', ',aa+ ', ',id+1)-id) b
into #t
from #,[table]
where substring( ', '+aa,id,1)= ', '

select * from #t

drop table #,#t
------解决方案--------------------
---创建存储过程
Create Proc Pro_Test
As
Set NoCount On
Declare @T Table(aa Varchar(20))
Insert @T Select aa From 表 ---表为你的目标表
---Declare @R Table(id int identity(1,1),aa Varchar(20))
While Exists(Select 1 From @T Where Replace(aa, ', ', ' ') <> ' ')
Begin
Insert 另一张表 Select Left(aa,CharIndex( ', ',aa)-1)
From @T Where Replace(aa, ', ', ' ') <> ' '
UPdate @T
Set aa=Stuff(aa+ ', ',1,CharIndex( ', ',aa), ' ')
End
Insert 另一张表 Select aa From @T Where Replace(aa, ', ', ' ') <> ' '
Go
---调用存储过程
Exec Pro_Test