日期:2014-05-19  浏览次数:20906 次

关于数据循环的一个问题
我的数据库是这样的:
id   field1
--------------
5       张三,2005-01-01
6       a,qer
7       b   kk
8       cdd
9       李四,2005-1-8
10       agr[fg0)
11       dhg
12       e3y
13       王五,2005-3-9
15       fhg
16       guy

现在要把日期插入到field1的每一行的开头,按照ID顺序进行。即结果如下
id   field1   field2
--------------
5       张三,     2005-01-01
6       a,qer       2005-01-01
7       b   kk       2005-01-01
8       cdd       2005-01-01
9       李四,2005-1-8
10       agr[fg0)       2005-1-8
11       dhg       2005-1-8
12       e3y       2005-1-8
13       王五,2005-3-9
15       fhg       2005-3-9
16       guy       2005-3-9

最好不用游标,请大家帮忙解决一下啊。速度要快一点的

------解决方案--------------------
create table T(id int, field1 varchar(50) collate CHINESE_PRC_CS_AI_WS)
insert T select 5, '张三,2005-01-01 '
union all select 6, 'a,qer '
union all select 7, 'b kk '
union all select 8, 'cdd '
union all select 9, '李四,2005-1-8 '
union all select 10, 'agr[fg0) '
union all select 11, 'dhg '
union all select 12, 'e3y '
union all select 13, '王五,2005-3-9 '
union all select 15, 'fhg '
union all select 16, 'guy '

declare @dt table(id int, field1 varchar(50), field2 datetime)
declare @id int, @field1 varchar(50), @field2 datetime
declare cur cursor local
for
select id, field1 from T

open cur
fetch next from cur into @id, @field1
while @@fetch_status=0
begin
if charindex( ', ', @field1 collate CHINESE_PRC_CS_AI_WS)> 0
begin
set @field2=right(@field1, len(@field1)-charindex( ', ', @field1))
set @field1=left(@field1, charindex( ', ', @field1))
end


insert @dt select @id, @field1, @field2

fetch next from cur into @id, @field1
end
close cur
deallocate cur

select * from @dt

--result
id field1 field2
----------- -------------------------------------------------- ------------------------------------------------------
5 张三, 2005-01-01 00:00:00.000
6 a,qer 2005-01-01 00:00:00.000
7 b kk 2005-01-01 00:00:00.000
8 cdd 2005-01-01 00:00:00.000
9 李四, 2005-01-08 00:00:00.000
10 agr[fg0) 2005-01-08 00:00:00.000
11 dhg 2005-01-08 00:00:00.000
12 e3y 2005-01-08 00:00:00.000
13 王五, 2005-03-09 00:00:00.000
15