select语句的问题

xiaomuwing 2005-11-29 08:28:05
表Table1(示例,实际表字段和记录都很多):

id col1 col2
1 1 a
2 null b
3 null c
4 null d
5 2 e
6 null f
7 null g
8 null h
9 null i
10 3 j

要得到的结果是:

id col1 col2
1 1 a
2 1 b
3 1 c
4 1 d
5 2 e
6 2 f
7 2 g
8 2 h
9 2 i
10 3 j

有没有什么比较快的办法?这个数据库很大,我用CURSOR游的太慢了
...全文
52 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhao606 2005-11-29
  • 打赏
  • 举报
回复
to:libin_ftsafe(子陌红尘)
佩服!!!!!!!!
xiaomuwing 2005-11-29
  • 打赏
  • 举报
回复
偶像!我拜你为师吧!!!
子陌红尘 2005-11-29
  • 打赏
  • 举报
回复
以上两种方法都可以实现,而之前的第一个回复是错的。
子陌红尘 2005-11-29
  • 打赏
  • 举报
回复
create table Table1(id int,col1 int,col2 char(1))
insert into Table1 select 1 ,1 ,'a'
insert into Table1 select 2 ,null,'b'
insert into Table1 select 3 ,null,'c'
insert into Table1 select 4 ,null,'d'
insert into Table1 select 5 ,2 ,'e'
insert into Table1 select 6 ,null,'f'
insert into Table1 select 7 ,null,'g'
insert into Table1 select 8 ,null,'h'
insert into Table1 select 9 ,null,'i'
insert into Table1 select 10,3 ,'j'


update a
set
col1 = (select top 1 col1 from Table1 where id<a.id and col1 is not null order by id desc)
from
Table1 a
where
col1 is null

select * from Table1
/*
id col1 col2
------------------
1 1 a
2 1 b
3 1 c
4 1 d
5 2 e
6 2 f
7 2 g
8 2 h
9 2 i
10 3 j
*/

drop table Table1
子陌红尘 2005-11-29
  • 打赏
  • 举报
回复
create table Table1(id int,col1 int,col2 char(1))
insert into Table1 select 1 ,1 ,'a'
insert into Table1 select 2 ,null,'b'
insert into Table1 select 3 ,null,'c'
insert into Table1 select 4 ,null,'d'
insert into Table1 select 5 ,2 ,'e'
insert into Table1 select 6 ,null,'f'
insert into Table1 select 7 ,null,'g'
insert into Table1 select 8 ,null,'h'
insert into Table1 select 9 ,null,'i'
insert into Table1 select 10,3 ,'j'


declare @i int
update table1
set
@i = (case when col1 is null then @i else col1 end),
col1 = @i


select * from Table1
/*
id col1 col2
1 1 a
2 1 b
3 1 c
4 1 d
5 2 e
6 2 f
7 2 g
8 2 h
9 2 i
10 3 j
*/

drop table Table1
子陌红尘 2005-11-29
  • 打赏
  • 举报
回复
declare @i int

update table1
set
@i = case when col1=@i then @i else col1 end,
col = @i

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧