Reputation:
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.
Upvotes: 2
Views: 551
Reputation: 1211
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.
Upvotes: 0
Reputation: 7189
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
Upvotes: 1