读书人

sql更新话语

发布时间: 2013-01-01 14:04:19 作者: rapoo

sql更新语句
同一张表中有男女两个人的名字相同,现在在相同的男生姓名前加上男,女生向明前加上女的sql语句怎么写?
急求,谢谢
[解决办法]


if OBJECT_ID('test') is not null
drop table test
go
create table test
(
name varchar(20),
sex varchar(2)
)
go
insert test
select '张三','男' union all
select '李四','男' union all
select '李四','女' union all
select '王五','男'
go

update test
set name=sex+name where exists(select 1 from test a
where a.name=test.name and a.sex<>test.sex)

select * from test

/*
namesex
--------------------------
张三男
男李四男
女李四女
王五男
*/

[解决办法]
引用:
只修改男的 男的姓名前加男就可以了 女生不用修改



if OBJECT_ID('test') is not null
drop table test
go
create table test
(
name varchar(20),
sex varchar(2)
)
go
insert test
select '张三','男' union all
select '李四','男' union all
select '李四','女' union all
select '王五','男'
go

update test
set name=sex+name where exists(select 1 from test a
where a.name=test.name and a.sex<>test.sex) and sex='男'

select * from test

/*
namesex
-------------------------
张三男
男李四男
李四女
王五男
*/


都写成这样了 还在问 貌似你完全不懂 或者就是懒

读书人网 >SQL Server

热点推荐