求一Sql语句

dbmanager_sp 2005-03-21 07:00:58
问题说明:
有一表(Table_Student)结构如下:
No. Name Sex ClassName
01 张三 男 一班
02 李四 男 二班
03 王屋 男 一班
04 小明 女 一班
.....

想通过一条语句实现 更新表中 ClassName字段,将一班更新为二班,更新条件 Sex='男',如果符合条件的记录多于两条,最多更新两条;

Update Table_Student set ClassName='二班' where Sex='男' 执行后将更新三条
我的问题是只更新 no.01 no.02 的记录.
不能用临时表。
...全文
170 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
goodluck001 2005-03-23
  • 打赏
  • 举报
回复
update Table_Student
set ClassName='二班'
where No. in
(
select top 2 No.
from Table_Student
where ClassName='一班' and
Sex='男'
)
yesyesyes 2005-03-22
  • 打赏
  • 举报
回复
xluzhong(打麻将一缺三,咋办?)的方法最简单
set rowcount 2
update t
set class='二班'
where sex='男'
set rowcount 0
完事
jiang130 2005-03-22
  • 打赏
  • 举报
回复
樓主的變通能為真強﹐建議看看行集函數相關資料
dbmanager_sp 2005-03-21
  • 打赏
  • 举报
回复
set rowcount 2 语句能不能不在存储过程中使用,比如在编程语言中?如果能,请举例,用Adodataset
dbmanager_sp 2005-03-21
  • 打赏
  • 举报
回复
jiang130:
另外,你的方法能不能简化成:

update a set ClassName='二班' from (select top 2 * from table_student where Sex='男') a

请进一步探讨,还有我比较关心的是性能问题。


xluzhong 2005-03-21
  • 打赏
  • 举报
回复
都没有用到临时表,思想都是把影响行设为两行!

---set rowcount 2 请看联机帮助@@ROWCOUNT
dbmanager_sp 2005-03-21
  • 打赏
  • 举报
回复
xluzhong:
第一种方法能不能说明白点。第二种方法不和题,要求不用临时表。
jiang130:
方法应该可行,但性能如何?该方法和建临时表有何区别?
谢谢答复
xluzhong 2005-03-21
  • 打赏
  • 举报
回复
------或者
create table t(no int,[name] nvarchar(10),sex nchar(1),class nvarchar(10))
insert into t
select '1','ralph','男','一班' union all
select '2','andy','男','二班' union all
select '3','terry','男','一班' union all
select '4','king','女','一班'


select * from t

set rowcount 2

update t
set class='二班'
where sex='男'

set rowcount 0

select * from t


drop table t
xluzhong 2005-03-21
  • 打赏
  • 举报
回复
create table t(no int,[name] nvarchar(10),sex nchar(1),class nvarchar(10))
insert into t
select '1','ralph','男','一班' union all
select '2','andy','男','二班' union all
select '3','terry','男','一班' union all
select '4','king','女','一班'


select * from t

update t
set class='二班'
from t a
where no in (select top 2 no from t where sex='男' order by no)

select * from t


drop table t
jiang130 2005-03-21
  • 打赏
  • 举报
回复
update a set ClassName='二班' from table_student a inner join (select top 2 * from table_student where Sex='男') b on a.no=b.no
xluzhong 2005-03-21
  • 打赏
  • 举报
回复
Update Table_Student
set ClassName='二班'
from Table_Student a
--where no in (select top 2 no from Table_Student where sex=a.sex and no<a.no order by no)
where no in (select top 2 no from Table_Student where sex='男' and no<a.no order by no)

27,579

社区成员

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

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