SQL: Trigger set column to null
I created a trigger to set a column to null where the column has a value greater than GETDATE()
ALTER TRIGGER [dbo].[Null_Time_Trigger3]
on [dbo].[Parking]
FOR insert
as
update Parking
set Column = NULL
from Parking
where Column >= CAST(GETDATE () AS TIME)
it appears when the time passes the trigger doesn't do anything? the time is still in the column and the column is not having the value of NULL
.
Any idea how to resolve this ??
Is there anyway to do this (Set开发者_如何学Pythonting the column to null) other than triggers???
Regards.
insert
triggers only fire on an insert statement. If there is no insert
operation your trigger will not run.
As your trigger references the Parking
table itself rather than the inserted
table it might work on insert but this is totally not what triggers are for.
There are no temporal triggers in SQL Server that would automatically NULL
-ify the columns when the time is passed (as it seems you might be expecting).
You can do CASE WHEN Column < CAST(GETDATE () AS TIME) THEN Column END AS Column
in your SELECT
instead.
First of all, I think you should use < in your trigger definition. Anyway this trigger is fired ONLY when you insert a new row in db and acts ONLY on that row, not on previous ones!!!
You could do that with one query:
UPDATE Parking SET `Column`=NULL
WHERE `Column` < CAST(GETDATE () AS TIME)
EDITED:
CREATE TRIGGER [dbo].[Null_Time_Trigger4]
on [dbo].[Parking]
FOR INSERT,UPDATE
AS BEGIN
UPDATE Parking SET `Column`=NULL
WHERE `Column` < CAST(GETDATE () AS TIME)
END
You could add a calculated column, something like this:
CREATE TABLE
(
...
Column DATETIME,
CurrentColumn AS CASE WHEN DATETIME < SYSDATETIME() THEN DATETIME END
....
)
However, in general you should log events as new records rather than updating an existing column. Your current design destroys information.
精彩评论