November 14, 2013 at 1:47 am
Hi Guys,
I need help with a trigger, I would like to prevent a user from inserting a blank string into a column.
At the moment the trigger below raises an error even when the txtDescription column is not blank.
Please help, I'm not sure what I'm missing:
CREATE TRIGGER trDtlIncident ON dbo.dtlIncident
AFTER INSERT
AS
IF EXISTS (SELECT * FROM dtlIncident
WHERE Convert(Varchar, txtDescription) <> '')
BEGIN
RAISERROR ('Incident description can not be blank.', 16, 1);
ROLLBACK TRANSACTION;
RETURN
END;
GO
Thanks
November 14, 2013 at 1:53 am
Your trigger is checking the entire table, not the rows just inserted. So if there's any blank values anywhere in the table, the trigger will fail. You probably want to use the inserted table in the exists, rather than the actual table name.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
November 14, 2013 at 2:05 am
That said, a check constraint would probably be a better choice than a trigger here.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
November 14, 2013 at 2:36 am
Thank you, I'll try your suggestions 🙂
November 14, 2013 at 2:52 am
I've joined the inserted table to the actual table as it's using a text column and it works perfectly. Thanks
ALTER TRIGGER trDtlIncident ON dbo.dtlIncident
AFTER INSERT
AS
IF EXISTS (SELECT * FROM inserted i, dtlIncident inc
WHERE Convert(Varchar, inc.txtDescription) = ''
AND i.uidId = inc.uidId)
BEGIN
RAISERROR ('Incident description can not be blank.', 16, 1);
ROLLBACK TRANSACTION;
RETURN
END;
GO
November 14, 2013 at 3:13 am
I still recommend considering a check constraint instead of the trigger.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply