dbTalk Databases Forums  

constraint in Trigger

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss constraint in Trigger in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
jay_wic@yahoo.com
 
Posts: n/a

Default constraint in Trigger - 05-03-2007 , 04:32 PM






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

Please Help.


Reply With Quote
  #2  
Old   
Erland Sommarskog
 
Posts: n/a

Default Re: constraint in Trigger - 05-03-2007 , 05:24 PM






(jay_wic (AT) yahoo (DOT) com) writes:
Quote:
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 (AT) sommarskog (DOT) se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.