Re: constraint in Trigger



(jay_wic@xxxxxxxxx) writes:
I do not know this is the correct way to do this, but somehow this
isnt working. All I want is not to have a null value in field A if
there is a value in field B

heres the code

CREATE TRIGGER tiu_name ON tblName
FOR INSERT, UPDATE
AS
DECLARE @FieldA AS REAL, @FieldB AS REAL;

SELECT @FieldA=FieldA, @FieldB=FieldB
FROM Inserted;

IF (@FieldB IS NOT NULL) AND (@FieldA IS NULL)
RAISERROR('Error Message',1,2);
GO

A common error with triggers: you assume that they fire once per row,
when they in fact fire once per statement. Thus, you cannot select into
variables, but you must work with the inserted table directly:

IF EXISTS (SELECT *
FROM inserted
WHERE fieldB IS NOT NULL and fieldA IS NULL)
BEGIN
ROLLBACK TRANSACTION
RAISERROR('Error message', 16, 1)
END

Note two other changes:

o Added ROLLBACK TRANSACTION to rollback back the statement that fired
the trigger.
o Increased the severity level from 1 to 16 in the RAISERROR statement.
Level 1-10 are informational only. Level 11 or higher raises an error.

Finally, there is a simpler solution, without a trigger, in this case.
Just add a table constraint:

CONSTRAINT ckt_nullcheck CHECK
(NOT (fieldB IS NOT NULL AND fieldA IS NULL))

--
Erland Sommarskog, SQL Server MVP, esquel@xxxxxxxxxxxxx

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
.



Relevant Pages

  • Calculated field in a calculation.
    ... FieldA = FieldB + FieldC ... FieldC = FieldD - FieldE, ... I would like to move to SQL Server Stored Procs have SQL ...
    (microsoft.public.sqlserver.mseq)
  • Re: insert variables into Query
    ... Learning SQL and Access ... from tableX ... fieldA <= tableY.EndDate ... fieldB>= tableY.EndDate ...
    (microsoft.public.access.queries)
  • Re: Forms - Mandatory field
    ... me to use a real e-mail address in public newsgroups. ... GlobalSign digital certificate is a forgery and should be deleted without ... FieldA and FieldB. ...
    (microsoft.public.access.forms)
  • Re: insert variables into Query
    ... on the date in your [EndDate] field? ... fieldA <= tableY.EndDate ... fieldB>= tableY.EndDate ... SQL iteration 1: ...
    (microsoft.public.access.queries)
  • Re: Percentage at group level of Crystal Report.
    ... FieldC is a formula field, dividing FieldA by FieldB. ... > as to how to create a group level value for FieldC, ...
    (microsoft.public.vb.crystal)