日期:2014-05-18  浏览次数:20588 次

求助:将已删除的信息发到一个另外的表中,如何实现?
需求是这样的:有一个学生信息表:StudentInfo,现要求每删除一个学生,都将这个学生的信息放到一个新的表中。
我的想法是这样的:新建一个StudentInfo_old表,用于存储那些被删除的学生,这个表的结构和StudentInfo一样,再在StudentInfo表上建立一个触发器,这个触发器的功能是每删除一个学生都将这个被删除的学生信息发到StudentInfo_old中。
现有两个问题求助高手:
1、如何复制StudentInfo表为StudentInfo_old,其结构完全一样。我的操作方法是在企业管理器中右键表-> 复制(此时复制的是这个表的create   table的SQL语句),然后到查询分析器里创建StudentInfo_old表。不知这种做法是否正确,有无更好的做法?
2、上面所提到的触发器该如何创建?(求创建的SQL语句)

------解决方案--------------------
--生成表StudentInfo_old
select * into StudentInfo_old
from StudentInfo where 1=0
--删除的学生在新表生成
create trigger trStudentInfoDel on dbo.StudentInfo
for delete
as
insert StudentInfo_old from deleted

------解决方案--------------------
create trigger trStudentInfoDel on dbo.StudentInfo
for delete
as
insert StudentInfo_old select * from deleted--少了select *
------解决方案--------------------
1、如何复制StudentInfo表为StudentInfo_old,其结构完全一样。我的操作方法是在企业管理器中右键表-> 复制(此时复制的是这个表的create table的SQL语句),然后到查询分析器里创建StudentInfo_old表。不知这种做法是否正确,有无更好的做法?
--------------------------
这种方式很简单,但存在一个问题,表名前没有 dbo,不知道这是不是SQL Server的一个Bug。

另一种方法:

--> 选中表,右键,所有任务
--> 生成SQL脚本
--> 注意,要将“设置格式”中的“为每个对象生成 drop <对象> 命令”的勾去掉。
--> 在“选项”中,选择生成主键等选项。

------解决方案--------------------
create trigger tr_BackupDeletedData on dbo.StudentInfo
for delete
as
--注意:如果这个表中没有自动编号字段,可以如下处理。
--如果有自动编号字段,需要指定字段列表
insert StudentInfo_old
select *
from deleted
go

------解决方案--------------------
select *
into StudentInfo_old
from StudentInfo
where 1=0
------------------------------------
用一楼提供的这种方法不能带主键等属性信息。


1、复制生成SQL脚本。
2、右键生成SQL脚本。



------解决方案--------------------
为什么不追加个字段标识某学生记录是否被删除呢????
------解决方案--------------------
回楼上,这样会导致该项目中所有以前用到的查询学生记录的sql 语句都要做相应的更改,而且这样会导致学生信息表变得十分庞大,导致查询效率降低。
------解决方案--------------------
--生成表StudentInfo_old
select * into StudentInfo_old
from StudentInfo where 1=0
--删除的学生在新表生成
create trigger trStudentInfoDel on dbo.StudentInfo
for delete
as
insert StudentInfo_old select * from 数据库名..deleted
------解决方案--------------------
http://topic.csdn.net/t/20060216/16/4559979.html
------解决方案--------------------
--生成表StudentInfo_old
select * into StudentInfo_old
from StudentInfo where 1=2
--新表生成
create trigger TR_StudentInfoDel on dbo.StudentInfo
for delete
as
insert StudentInfo_old select * from deleted