I have an update trigger which runs if field 'urejeno' gets modified.
USE [MYDATABASE]
GO
create trigger trg_MyTrigger on dbo.mytable
after update
as
if @@ROWCOUNT = 0
return
set nocount on
if UPDATE (UREJENO)
update mytable
set UREJENO_KDAJ = getdate(),
UREDIL_KDO = USER_NAME()
from mytable S
inner join Inserted I on S.TW_ID = I.TW_ID
However I would like to add a condition so that if 'urejeno' = True the trigger does what is described above but if the condition is 'False' I want to set the mentioned fields to NULL.
What must I change ?
You could add another update query in an else part of the conditional, or you could rewrite your update and use the bit value as the conditional directly.
This should work (if I understood you intent correctly).
CREATE TRIGGER trg_MyTrigger ON dbo.mytable
AFTER UPDATE
AS
IF @@ROWCOUNT = 0
RETURN
SET NOCOUNT ON
IF UPDATE(UREJENO)
BEGIN
UPDATE mytable
SET
UREJENO_KDAJ = CASE WHEN I.UREJENO = 1 THEN GETDATE() ELSE NULL END,
UREDIL_KDO = CASE WHEN I.UREJENO = 1 THEN USER_NAME() ELSE NULL END
FROM mytable S
INNER JOIN Inserted I on S.TW_ID = I.TW_ID
END
GO
This would set the two fields to null if UREJENO was updated to 0 (false), but UREJENO was set to 1 (true) then getdate() and user_name() would be used.