SQL在插入触发器中将datediff分配给表列

时间:2015-10-30 01:59:30

标签: sql sql-server triggers sql-server-2012

表格

CREATE TABLE CurrentApplication
(
    StartDate       datetime        NOT NULL,
    EndDate         datetime        NOT NULL,
    NoOfDays        integer,
    StaffID         integer         NOT NULL,
    AppStatus       varchar(30)     NOT NULL    DEFAULT 'PENDING'
)

插入触发器

CREATE TRIGGER InsertNoOfDays ON CurrentApplication
AFTER INSERT
BEGIN
INSERT INTO CurrentApplication
    NoOfDays AS Datediff(day, StartDate, EndDate)
END

我有NoOfDays列,它应该在StartDate和EndDate之间保存DateDiff,并且只要将新记录插入表中,就应该插入值。如何编写触发器并执行此操作?我尝试过,但我的触发器无法正常工作。谢谢!

3 个答案:

答案 0 :(得分:1)

一种方法是使用INSTEAD OF触发器:

CREATE TRIGGER InsertNoOfDays ON CurrentApplication
INSTEAD OF INSERT AS
BEGIN
    INSERT INTO CurrentApplication( . . ., NoOfDays)
        SELECT . . ., 
               Datediff(day, StartDate, EndDate)
        FROM inserted;
END;

答案 1 :(得分:0)

您可以做的一件事是将计算列而不是实际列添加为NoOfdays。

添加计算列有一些好处和缺点。

您没有触发器并进行计算。保存写入。 这也意味着有时您无法对该列进行索引,并且读取可能会产生影响。

以下是Microsoft关于计算列的文档(文档说它仅在SQL 2016之后): Specify Computed Columns in Tables

但是,这里的SQL 2014中的示例对我有用(我认为它也适用于SQL 2012)

use tempdb
GO
/*
    Wors in version:

    Microsoft SQL Server 2014 - 12.0.2000.8 (X64) 
    Standard Edition (64-bit
*/
IF OBJECT_ID('tempdb.dbo.CurrentApplication') IS NULL
    CREATE TABLE dbo.CurrentApplication
    (
        StartDate       datetime        NOT NULL,
        EndDate         datetime        NOT NULL,
        NoOfDays        AS (datediff(dd, StartDate, EndDate)) PERSISTED,
        StaffID         integer         NOT NULL,
    )

INSERT INTO dbo.CurrentApplication(StartDate, EndDate, StaffId)
SELECT TOP 10 
         StartDate   =   DATEADD(dd, object_id, '1/1/2017')
        ,EndDate     =   DATEADD(dd, object_id*object_id, '1/1/2017')
        ,StaffId =   object_id
FROM    sys.objects 
WHERE   object_id < 300
order by Object_id

SELECT * FROM CurrentApplication

IF OBJECT_ID('tempdb.dbo.CurrentApplication') IS NOT NULL
    DROP TABLE dbo.CurrentApplication

答案 2 :(得分:0)

由于没有资格添加评论,因此添加为新答案。

添加到@Gordon Linoff的答案,只是替换了列名而不是句号来查看是否会导致您获得错误。我没有得到那个错误。不确定SQL 2012是否有任何内容。

但是,这有效(在SQL 2014中):

CREATE TRIGGER InsertNoOfDays ON dbo.CurrentApplication
INSTEAD OF INSERT AS
BEGIN
    INSERT INTO CurrentApplication(StartDate, EndDate, NoOfDays, StaffID)
        SELECT  StartDate
               ,EndDate 
               ,Datediff(dd, StartDate, EndDate)
               ,StaffId
        FROM inserted as i;
END;