创建SQL Server触发器错误

时间:2014-11-28 17:16:59

标签: sql sql-server triggers

我收到错误,无法弄清楚我做错了什么。我正在桌面上创建一个触发器来每天存档此表。该表被截断,每天早上插入新数据。一旦发生这种情况,我想将其存档。

这是我创建触发器的代码:

IF OBJECT_ID('trg_archive_inventory_table') IS NOT NULL
   DROP TRIGGER trg_archive_inventory_table
GO

CREATE TRIGGER trg_archive_inventory_table 
ON inventory 
AFTER INSERT
AS 
BEGIN
   SET NOCOUNT ON;

   /* delete data from one year ago */
   DELETE FROM [cadc].[dbo].[inventory_archive] 
   WHERE entry_date = CAST((DATEADD(yy, -1, GetDate())) as DATE);

   /* insert todays inventory */
   INSERT INTO [cadc].[dbo].[inventory_archive] (sku, tag_id , load_id, batch, status, qc_status, location, eaches, units, cartons, r_date, e_date, zone_1, zone_2, loc_type, loc_pick, mod_time, receiver_no, mfg_code, each_unit, unit_carton)
       SELECT 
           sku, tag_id , load_id, batch, status, qc_status, location, eaches, 
           units, cartons, r_date, e_date, zone_1, zone_2, loc_type, loc_pick, 
           mod_time, receiver_no, mfg_code, each_unit, unit_carton 
       FROM 
           [cadc].[dbo].[inventory];
END

我一直收到以下错误:

  

'CREATE / ALTER TRIGGER'不允许将数据库名称指定为对象名称的前缀。

我还尝试使用[cadc].[dbo].[inventory]为库存表添加前缀,但收到同样的错误。

谷歌搜索有助于理解这个问题。

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

我需要将数据库设置在触发器上方

IF OBJECT_ID('trg_archive_inventory_table') IS NOT NULL
DROP TRIGGER trg_archive_inventory_table
GO

USE cadc;
GO

CREATE TRIGGER trg_archive_inventory_table ON  inventory AFTER INSERT
AS 
BEGIN
SET NOCOUNT ON;
DECLARE @lastrun date;

/* make sure the inventory table was updated this morning*/ 
SELECT @lastrun = MAX(entry_date) FROM [cadc].[dbo].[inventory_archive];

IF (@lastrun < CAST(GETDATE() as date))
BEGIN
    /* delete data from one year ago */
    DELETE FROM [cadc].[dbo].[inventory_archive] WHERE entry_date = CAST((DATEADD(yy, -1, GetDate())) as DATE);

    /* insert todays inventory */
    INSERT INTO [cadc].[dbo].[inventory_archive] (sku, tag_id , load_id, batch, status, qc_status, location, eaches, units, cartons, r_date, e_date, zone_1, zone_2, loc_type, loc_pick, mod_time, receiver_no, mfg_code, each_unit, unit_carton)
        SELECT sku, tag_id , load_id, batch, status, qc_status, location, eaches, units, cartons, r_date, e_date, zone_1, zone_2, loc_type, loc_pick, mod_time, receiver_no, mfg_code, each_unit, unit_carton 
        FROM [cadc].[dbo].[inventory];
END
END

如上所述@marc_s我将尝试将其移至运行的作业。