|
|
|
Forum Newbie
      
Group: General Forum Members
Last Login: Thursday, April 04, 2013 11:02 AM
Points: 4,
Visits: 9
|
|
I have the following to create a trigger. But get this error message: Msg 207, Level 16, State 1, Procedure triggername, Line 7 Invalid column name 'field1'. Msg 207, Level 16, State 1, Procedure triggername, Line 7 Invalid column name 'field2'.
One other question..why do I have to include the 16,1 after my text for the error in the raiserror statement ( RAISERROR ('Text of error',16,1)?
SQL statement
CREATE TRIGGER triggername ON tablename AFTER INSERT, UPDATE AS BEGIN IF ([field1]=1 and [field2] Is Null) BEGIN ROLLBACK TRANSACTION RAISERROR ('Text of error',16,1) End END GO
|
|
|
|
|
SSChampion
        
Group: General Forum Members
Last Login: Today @ 1:11 PM
Points: 11,605,
Visits: 27,645
|
|
your trigger needs to refer to a table, just like any other SELECT statement does; when inside a trigger, you need to use the virtual tables INSERTED or DELETED, depending on the operation you are testing. something like this is what you are after, i think:
CREATE TRIGGER triggername ON tablename AFTER INSERT, UPDATE AS BEGIN IF EXISTS(SELECT 1 FROM INSERTED WHERE ( [field1] = 1 --this column must actually exist in the table AND [field2] IS NULL )) --this column must actually exist in the table BEGIN ROLLBACK TRANSACTION RAISERROR ('Text of error: Field2 cannot be null when Field1 has a value of one.',16,1) END END GO
For the Why 16 question, any error greater than 16 is "Severe" enough to rollback a calling transaction as well.
Lowell
--There is no spoon, and there's no default ORDER BY in sql server either. Actually, Common Sense is so rare, it should be considered a Superpower. --my son
|
|
|
|
|
Forum Newbie
      
Group: General Forum Members
Last Login: Thursday, April 04, 2013 11:02 AM
Points: 4,
Visits: 9
|
|
|
|
|
|
SSCommitted
      
Group: General Forum Members
Last Login: Tuesday, January 15, 2013 11:11 AM
Points: 1,945,
Visits: 2,782
|
|
The goal of good SQL programmers is to write only declarative code, so we avoid triggers like cannibalism; a last desperate tool used only as a last resort. They are highly propriety in T-SQL, cannot be optimized and make your code look like 1960's BASIC or COBOL 
You can do this with a simple check constraint. This will help the optimizer, but you have to catch the error, so use a good constraint name
CONSTRAINT bad_foobar CHECK (NOT (field1 = 1 AND field2 IS NULL))
Books in Celko Series for Morgan-Kaufmann Publishing Analytics and OLAP in SQL Data and Databases: Concepts in Practice Data, Measurements and Standards in SQL SQL for Smarties SQL Programming Style SQL Puzzles and Answers Thinking in Sets Trees and Hierarchies in SQL
|
|
|
|