求一条sql server 语句!急急急

persist_yu20082009 2010-07-22 01:29:43
表有2个字段 worknum , date
新增一条记录时,给出 worknum 和date 值 如: 1234 , 2010-04-21
如果worknum列有1234这个值,就更新 该记录的 date记录
如果worknum列没有1234这个值,就新增一条记录。
请大家给出语句,万分感激!!!

...全文
78 点赞 收藏 6
写回复
6 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
njlywy 2010-07-22
if exists (select 1 from tb where worknum = 1234)
begin
update tb
set date = ' 2010-04-21'
where worknum = 1234
end
else
insert into tb ( worknum, date )values (1234 , '2010-04-21')
回复
s_111111 2010-07-22
各位大俠,有一個merge用法 不知道可行不可行。
回复
无涯大者 2010-07-22
写个存储过程
1.创建表tbA
create table tbA(
worknum int,
date datetime
)

2.创建存储过程
create  PROC pro_insert(@worknum int,@date datetime)
as
if exists (select 1 from tbA where worknum = @worknum)
begin
update tbA set date = @date where worknum =@worknum
end
else
insert into tbA ( worknum, date )values (@worknum , @date)
GO

3.直接调用存储过程
 Execute pro_insert '1234','2010-6-21'
回复
mechellerong 2010-07-22
 create table tb(
worknum int,
date datetime
)
insert into tb ( worknum, date )values (1234,'2010-04-21')
insert into tb ( worknum, date )values (1234,'2010-05-21')

select * from tb

结果如下:
----------------------------
Worknum date
1234 2010-04-21 00:00:00.000
1234 2010-05-21 00:00:00.000

if exists (select 1 from tb where worknum = 1234)
begin
update tb
set date = ' 2010-04-21'
where worknum = 1234
end
else
insert into tb ( worknum, date )values (1234,'2010-05-21')

结果如下:
--------------------------------------
Worknum date
1234 2010-04-21 00:00:00.000
1234 2010-04-21 00:00:00.000


回复
koolxiaoyuer 2010-07-22

CREATE PROCEDURE pinsert(
@worknum int,
@date datetime
)
as
if exists (select 1 from tb where worknum = @worknum )
begin
update tb
set date = @date
where worknum =@worknum
end
else
insert into tb ( worknum, date )values (@worknum , @date)
GO
回复
王向飞 2010-07-22
if exists (select 1 from tb where worknum = 1234)
begin
update tb
set date = ' 2010-04-21'
where worknum = 1234
end
else
insert into tb ( worknum, date )values (1234 , '2010-04-21')
回复
相关推荐
发帖
MS-SQL Server
创建于2007-09-28

3.3w+

社区成员

MS-SQL Server相关内容讨论专区
申请成为版主
帖子事件
创建了帖子
2010-07-22 01:29
社区公告
暂无公告