I have a table that contains two not null columns Created and Updated.
I wrote corresponding triggers
ALTER TRIGGER [dbo].[tr_category_inserted] ON [dbo].[Category]
AFTER INSERT
AS
BEGIN
UPDATE Category
SET Created = GETDATE(), Updated = GETDATE()
FROM inserted
WHERE Category.ID = inserted.ID;
END
and
ALTER TRIGGER [dbo].[tr_category_updated] ON [dbo].[Category]
AFTER UPDATE
AS
BEGIN
UPDATE Category
SET Updated = GETDATE()
FROM inserted
inner join [dbo].[Category] c on c.ID = inserted.ID
END
but if I am inserting a new row I get an error
Cannot insert the value NULL into column ‘Created’, table
‘Category’; column does not allow nulls. INSERT fails.
Insert command:
INSERT INTO [Category]([Name], [ShowInMenu], [Deleted])
VALUES ('category1', 0, 0)
How can I write such triggers without a setting to these columns to allow null?
Modify your table like this:
Set the default for the created to column to 0. Unfortunately MySQL does not allow two timestamp columns with default
CURRENT_TIMESTAMPin one table. To overcome this you just have to insert aNULLvalue intocreatedcolumn and you will have both columns to the current timestamp.Or you set the default to a valid timestamp like
and modify your trigger like this: