all groups > sql server (alternate) > april 2005 >
You're in the

sql server (alternate)

group:

instead-of trigger and contraints


instead-of trigger and contraints Stuart McGraw
4/21/2005 3:04:03 PM
sql server (alternate):
Is Microsoft full of #*$#*% (again) or am I badly misunderstanding
something?

Quote from Microsoft's T-SQL doc:
[quoted text, click to view]
(SQL Server 2000 sp3a)

CREATE TABLE t (
a INT PRIMARY KEY,
b CHAR(1) NOT NULL)

I want to override the value of [b] with the value of 'X' when
inserting into t...

CREATE TRIGGER t_tbi ON t INSTEAD OF INSERT AS BEGIN
SET NOCOUNT ON
INSERT INTO t (a,b) (SELECT a,'X' FROM inserted)
END

Let's try it...

INSERT INTO t (a,b) VALUES(1,'z')
SELECT * FROM t
a | b
---|---
1 | X

Good, the trigger did what it was supposed to. Lets try a
slight variation...

INSERT INTO t (a) VALUES(2)
Server: Msg 233, Level 16, State 2, Line 1
The column 'b' in table 't' cannot be null.

WTF? What was that I just read about "[instead-of triggers]
are executed before any constraints"?!?!

What's going on here???
Re: instead-of trigger and contraints Quentin Ran
4/21/2005 4:32:49 PM
Stuart,

I am not sure you got the right document. I can not locate your quote in
BOL, and the quote "These triggers are executed after the inserted and
deleted tables reflecting the changes to the base table are created, but
before any other actions are taken." is clearly not correct. MS is not that
stupid.

Can you provide the way you found the quote?

Quentin

[quoted text, click to view]

Re: instead-of trigger and contraints MGFoster
4/21/2005 10:03:17 PM
[quoted text, click to view]

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Constraints are:

CREATE TABLE t (a char(1) CHECK (a <> 'z'))

The CHECK is the constraint that makes sure the column [a] cannot have
the value 'z' stored in it.

Other CONSTRAINTS are Primary Key, Foreign Key and Default.
--
MGFoster:::mgf00 <at> earthlink <decimal-point> net
Oakland, CA (USA)

-----BEGIN PGP SIGNATURE-----
Version: PGP for Personal Privacy 5.0
Charset: noconv

iQA/AwUBQmgjI4echKqOuFEgEQJXQwCfcU9SQ/m9WrZOEih+5db3sbiLg9AAnAky
oxV+MzTp3DTqgwvySrLyhtRc
=BGR+
Re: instead-of trigger and contraints Jacco Schalkwijk
4/21/2005 10:49:44 PM
NOT NULL is not a constraint, it is a property of the column definition, the
same as the datatype. INSERT INTO t(a,b) VALUES (1,'aa') will give an error
as well. The INSERT statement still get validated against the columns.

Check constraints, foreign keys etc don't get checked before the trigger
though:

CREATE TABLE t (
a INT PRIMARY KEY,
b CHAR(1) NOT NULL)

GO
CREATE TRIGGER t_tbi ON t INSTEAD OF INSERT AS BEGIN
SET NOCOUNT ON
INSERT INTO t (a,b) (SELECT a,'X' FROM inserted)
END

GO
ALTER TABLE t ADD CONSTRAINT c CHECK ( b='x')
GO

INSERT INTO t(a,b) VALUES (1,'a')

GO
DROP TABLE t

--
Jacco Schalkwijk
SQL Server MVP


[quoted text, click to view]

AddThis Social Bookmark Button