![](/img/trans.png)
[英]how to copy data from multiple rows of one table to another in sql server?
[英]how to copy and delete data from multiple table of sql server
我有一個這樣的表:該表的名稱為Transaction_tbl。 像這樣的領域:
transactid Tbarcode dtime
1 100 2013-04-16 14:15:47.243
2 101 2013-05-10 10:15:47.243
3 102 2014-02-20 02:15:48.000
在這張桌子上
transactid is primary key
我還有一個這樣的表:該表名稱是KHanger_tbl.field,如下所示:
transactid Hbarcode
1 21
2 22
3 23
在我的KHanger_tbl中,這個transactid is the foregin key
我想將日期范圍<= 2013-12-30的數據從Transaction Table移動到另一個名為Transaction2013的表。(我的意思是2013年的數據)
同時相應的Khanger_table數據需要移動稱為Khanger2013 ..的表。此后,我想從Transaction_tbl表中刪除2013年數據,並從Khanger_tbl表中也刪除相應數據。
我該怎么做? 任何幫助都是非常明顯的..謝謝..
create table Transaction2013
as
select * from Transaction_tbl
where dtime <='2013-12-30' ;
create table Khanger2013 as
select * from Khanger_table
inner join Transaction_tbl
on Transaction_tbl.transactid=Khanger_table.transactid
and Transaction_tbl.dtime <='2013-12-30' ;
delete from Transaction_tbl
where dtime <='2013-12-30' ;
delete from Khanger_table
where exists (select 1 from Khanger_table
inner join Transaction_tbl
on Transaction_tbl.transactid=Khanger_table.transactid
and Transaction_tbl.dtime <='2013-12-30') ;
我認為您可以通過使用觸發器來做到這一點,為Transaction_tbl表創建刪除觸發器,因為您說“與此同時,對應的Khanger_table數據需要移動名為Khanger2013的表”
創建觸發器[dbo]。[trgTransaction_tblForMove]開啟Transaction_tbl
刪除
如
if (select dtime from deleted)<='2013-12-30' begin
insert into Transaction2013
select * from deleted
insert into Khanger2013
select * from KHanger_tbl KH
inner join deleted D on KH.transactid = D.transactid
delete KHanger_tbl
where transactid in (select transactid from deleted)
end
寫這樣的查詢:
select * into Transaction2013
from Transaction_tbl
where dtime <='2013-12-30'
select k.transactid,k.tid,k.Requested,k.HBarcode,k.Reqloc,k.Delivered into Khanger2013
from KHanger_tbl k
inner join Transaction_tbl t
on t.transactID=k.transactid
where t.dtime <='2013-12-30'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.