简体   繁体   中英

SQL Server 2012 Insert DATEDIFF into column trigger whenever a new record is inserted

Table

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

Trigger

CREATE TRIGGER InsertNoOfDays ON CurrentApplication
AFTER INSERT
AS
BEGIN
    DECLARE @temp INT

    SELECT @temp = DATEDIFF(day, EndDate, StartDate)
    FROM inserted

    INSERT INTO CurrentApplication(NoOfDays) VALUES (@temp)

    --SELECT StaffID = inserted.StaffID
    --FROM inserted

 --   INSERT INTO CurrentApplication(NoOfDays)
 --       SELECT Datediff(day, EndDate, StartDate)
 --       FROM inserted;
END

Error message:

Msg 515, Level 16, State 2, Procedure InsertNoOfDays, Line 10
Cannot insert the value NULL into column 'StartDate', table 'StaffPortalDB.dbo.CurrentApplication'; column does not allow nulls. INSERT fails. The statement has been terminated.

What I'm trying to do is I have a table CurrentApplication and I want the NoOfDays column to automatically be populated whenever a user inserts a new row, with the date difference of start day and end day.

IF Sql server Try inserting some default or dummy values,since its not null column

Some thing like this:

CREATE TRIGGER InsertNoOfDays ON CurrentApplication
AFTER INSERT
AS
BEGIN
    DECLARE @temp INT

    SELECT @temp = coalesce(DATEDIFF(day, EndDate, StartDate),0) --Default 0
    FROM inserted

    INSERT INTO CurrentApplication(NoOfDays) VALUES (@temp)

    --SELECT StaffID = inserted.StaffID
    --FROM inserted

 --   INSERT INTO CurrentApplication(NoOfDays)
 --       SELECT Datediff(day, EndDate, StartDate)
 --       FROM inserted;
END

It's because your Insert statement is attempting to insert a record but isn't inserting any values into the columns that cannot be empty (StartDate, EndDate, StaffID, AppStatus). For this insert to succeed you need to either change the INSERT statement to insert a value into these columns or change the table schema to allow NULL values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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