简体   繁体   English

触发从活动表中删除旧记录并插入到历史表中

[英]Trigger To delete Old Records from active table and Insert to history table

sql server 2008 SQL Server 2008中

May anyone share their expertise how to achieve the below scenario 愿任何人分享他们的专业知识如何实现以下方案

I have two table. 我有两个桌子。 active and history both have same structure. 活动和历史都具有相同的结构。

What I am trying to achieve, whenever new record insert to active table, whatever records existing in active table move to history. 我试图实现的目标是,每当新记录插入到活动表中时,活动表中存在的任何记录都会移到历史记录中。

I am trying to hold only current active records 我正在尝试仅保留当前活动记录

I have a column called fetch date and if any record have fetch date not same as getdate must be moved to history table. 我有一列称为获取日期,如果有记录具有与获取日期不同的获取日期,则必须将其移至历史记录表。 those record should not present in Active table. 这些记录不应出现在活动表中。

Thanks 谢谢

you have several syntax error there. 你那里有几个语法错误。

I am merely correcting the syntax 我只是在纠正语法

CREATE PROCEDURE BACKUP_TB 
    @tbname varchar(MAX) 
AS 
 BEGIN 
    SET nocount ON; 
    DECLARE @query varchar(MAX) 
    SET @query = 'select * into '+ @tbname + '_backup from ' + @tbname + ''; 
    EXEC (@query) 
    SET nocount OFF; 
END 

few issues you should take note 您应该注意的几个问题

  1. SELECT INTO <table name> will create new table and insert the result. SELECT INTO <table name>将创建新表并插入结果。 It will only works once. 它只会工作一次。 Then second time you run it, it will give error as the target table already existed. 然后第二次运行它,因为目标表已经存在,它将给出错误。 You should use pre-create all necessary tables and use insert into backup_table ( <column list> ) select <column list> from original_table 您应该使用预先创建的所有必要表,并使用insert into backup_table ( <column list> ) select <column list> from original_table

  2. Avoid using SELECT * , it is best practice to specify the column name explicitly 避免使用SELECT * ,最好的做法是显式指定列名

  3. If you have to use Dynamic SQL, do read up more about it. 如果必须使用Dynamic SQL,请阅读有关它的更多信息。 Example : The Curse and Blessings of Dynamic SQL . 示例: 动态SQL的诅咒和祝福 And take note of possible SQL Injection attack. 并注意可能的SQL注入攻击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM