求:从一table向另一table插入语句!

jblz 2005-09-09 08:10:00
一个库的两个表:
table1字段:indate id age sub ....
table2字段:DATE id F1 F2 F3 F4 ....

我想在在table1中添加记录的同时,判断table2中有没有ID跟table1中ID相同的记录,
一库中两个不同table:
table1字段:indate id age sub ....

2005-09-08 3456 23 A

table2字段: DATE id f1 f2 ....

200509 3456 null null
如没有,就在table2中也添加记录:只取table1中的年indate中的年和月,如2005-09-08取到talble2中就为200509就行了,id也要取一样的, 而其它的为空!

如table1中的indate=2005-09-08修改为了2005-08-30, 那么table2中的DATE也要改为200508.其它的记录(如F1 F2)不管

谢谢!
...全文
126 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
jblz 2005-09-09
  • 打赏
  • 举报
回复
自己顶一下
whisht 2005-09-09
  • 打赏
  • 举报
回复
触发器
vivianfdlpw 2005-09-09
  • 打赏
  • 举报
回复
去相应的版面询问。比如你用C++,就去C++版
jblz 2005-09-09
  • 打赏
  • 举报
回复
我想在程序里实现呢?
或用个循环判断是不是可以呢?
vivianfdlpw 2005-09-09
  • 打赏
  • 举报
回复
create trigger tr
on table1
for insert,update
as
begin tran

--插入不存在的
if not exists(select 1 from deleted)
begin
insert table2(id,[DATE])
select id,replace(left(indate,7),'-','') from inserted
end
else
begin
if update(indate)
begin
update table2
set [DATE]=replace(left(I.indate,7),'-','')
from table2 A
join inserted I on A.id=I.id
end
end

if @@error=0
begin
commit tran
end
else
begin
rollback tran
raiserror('操作失败,错误号码为%d',12,1,@@error)
end
go
wgsasd311 2005-09-09
  • 打赏
  • 举报
回复
create trigger ti_table1 on tabble1
for insert,update
as
if not exists(select 1 from deleted) --插入
insert into table2 (date,id)
select indate,id from inserted

if exists(select 1 from deleted) --删除
begin
if update(indate)
update table2 set [date]=b.indate from table2 a,inserted b where a.id=b.id

end

go
云中客 2005-09-09
  • 打赏
  • 举报
回复
做个触发器,简单用语句不能实现
develop000 2005-09-09
  • 打赏
  • 举报
回复
帮你顶

5,388

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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