473,322 Members | 1,405 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Trigger

I have been instructed to write a trigger that effectively acts as a foreign
key. The point (I think) is to get me used to writing triggers that dont
use the primary key(s)

I have created the following trigger

create trigger chk_team
on teams
for insert as
declare @chkCountry as char(2)
select @chkCountry = (select country from INSERTED)
-- if @@ROWCOUNT =0 RETURN
If @chkCountry NOT IN
(select distinct country from teams)
BEGIN
raiserror('Impossible country entered', 16, 1)
ROLLBACK TRANSACTION
END

However I tested it with the following insert statement

insert into teams values (15, 'London Paris', 'UK', 'Clive Woodward', 0,
NULL)

Which (unfortunately) works, IOW the above insert statement should cause the
error I specified as 'UK' does not exist in the set "select distinct
country from teams"

Any help appreciated
May 20 '07 #1
7 3261
Shane wrote:
I have been instructed to write a trigger that effectively acts as a
foreign
key. The point (I think) is to get me used to writing triggers that dont
use the primary key(s)

I have created the following trigger

create trigger chk_team
on teams
for insert as
declare @chkCountry as char(2)
select @chkCountry = (select country from INSERTED)
-- if @@ROWCOUNT =0 RETURN
If @chkCountry NOT IN
(select distinct country from teams)
BEGIN
raiserror('Impossible country entered', 16, 1)
ROLLBACK TRANSACTION
END

However I tested it with the following insert statement

insert into teams values (15, 'London Paris', 'UK', 'Clive Woodward', 0,
NULL)

Which (unfortunately) works, IOW the above insert statement should cause
the error I specified as 'UK' does not exist in the set "select distinct
country from teams"

Any help appreciated
I have got the triger working as I desire, however now I am perplexed as to
*why* it works..
The (new) trigger reads:

create trigger chk_team
on teams
for insert as
declare @chkCountry as char(2)
select @chkCountry = (select country from INSERTED)
-- if @@ROWCOUNT =0 RETURN
If @chkCountry IN
Â* Â* Â* Â* (select distinct country from teams)
BEGIN
Â* Â* Â* Â* raiserror('Impossible country entered', 16, 1)
Â* Â* Â* Â* ROLLBACK TRANSACTION
END
I am now _seriously_ confused
--
Q: Who knows everything there is to be known about vector analysis?
A: The Oracle of del phi!

May 20 '07 #2
Shane wrote:
I am now _seriously_ confused
The trigger fires *after* an insert has taken place, therefore in the
second case the trigger rollsback because the country does now indeed exist
in the subquery

Any ideas?

--
Q: What does a mathematician present to his fiancée when he wants to
propose?
A: A polynomial ring!

May 20 '07 #3
Hello, Shane

When you write triggers, you should not assume that the INSERTED table
will always contain only one row.

Let's consider the following DDL and sample data:

CREATE TABLE Countries (
CountryCode char(2) PRIMARY KEY, --ISO 3166-1 alpha 2
CountryName varchar(50) UNIQUE
)

INSERT INTO Countries VALUES ('US','United States')
INSERT INTO Countries VALUES ('GB','United Kindom')
INSERT INTO Countries VALUES ('FR','France')
INSERT INTO Countries VALUES ('RO','Romania')

CREATE TABLE teams (
TeamName varchar(50) PRIMARY KEY,
CountryCode char(2) --REFERENCES Countries
)

I would write the following trigger:

CREATE TRIGGER teams_IU_CheckCountry ON teams
FOR INSERT, UPDATE
AS
IF @@ROWCOUNT>0 AND UPDATE(CountryCode) BEGIN
IF EXISTS (
SELECT * FROM inserted
WHERE CountryCode NOT IN (SELECT CountryCode FROM Countries)
) BEGIN
RAISERROR ('Incorrect country code !',16,1)
ROLLBACK
RETURN
END
END

We can check how it works using these statements:

INSERT INTO teams VALUES ('Chicago Bulls', 'US')
INSERT INTO teams VALUES ('Steaua Bucuresti', 'RO')

INSERT INTO teams SELECT Team, 'GB' FROM (
SELECT 'Manchester United' Team
UNION ALL SELECT 'Arsenal'
) x

INSERT INTO teams VALUES ('Juventus', 'IT')
--the last INSERT will fail because we have not entered the country
code for Italy

However, this trigger is not enough to ensure referential integrity,
we also need a trigger for the Countries table:

CREATE TRIGGER countries_UD_CheckTeams ON Countries
FOR UPDATE, DELETE
AS
IF @@ROWCOUNT>0 BEGIN
IF EXISTS (
SELECT * FROM teams
WHERE CountryCode IN (SELECT CountryCode FROM deleted)
AND CountryCode NOT IN (SELECT CountryCode FROM Countries)
) BEGIN
RAISERROR('This country code is used by a team !',16,1)
ROLLBACK
RETURN
END
END

GO
DELETE Countries WHERE CountryCode='FR'
-- works OK

DELETE Countries WHERE CountryCode='RO'
-- error, because we have a team

Of course, instead of using such triggers, it's much more prefferable
to have real foreign keys, because of performance reasons (both for
modifications and SELECT-s), ease of development (why write 20 lines
of code when you can write 2 words?), functionality (we can create a
cascading FK), etc.

Razvan

May 20 '07 #4
Shane wrote:
Shane wrote:
>I am now _seriously_ confused

The trigger fires *after* an insert has taken place, therefore in the
second case the trigger rollsback because the country does now indeed exist
in the subquery

Any ideas?
That is one of the major problems with a product that only has AFTER
triggers. In those products that have both BEFORE and AFTER triggers,
AFTER triggers are used for auditing and BEFORE triggers used for
security and integrity. Essentially you are trying to do the right
thing, in the wrong way, in a product that truly doesn't support it.

Turn what you are doing into a multiuser environment with hundreds
or thousands of simultaneous users and it is a nightmare. Perhaps a
good learning experience ... but a nightmare.
--
Daniel A. Morgan
University of Washington
da******@x.washington.edu
(replace x with u to respond)
www.psoug.org
May 20 '07 #5
DA Morgan (da******@psoug.org) writes:
>The trigger fires *after* an insert has taken place, therefore in the
second case the trigger rollsback because the country does now indeed
exist in the subquery

Any ideas?

That is one of the major problems with a product that only has AFTER
triggers. In those products that have both BEFORE and AFTER triggers,
AFTER triggers are used for auditing and BEFORE triggers used for
security and integrity. Essentially you are trying to do the right
thing, in the wrong way, in a product that truly doesn't support it.
Actually, SQL Server also has INSTEAD OF triggers, which is not really
the same thing as an BEFORE trigger. Since an INSTEAD OF trigger requires
you to redo the action that trigger it, it less apetizing for checks -
unless the check is of the kind "DELETE is not permitted on this table".

But a BEFORE trigger would not have help Shane, as his trigger seemed to
perform a check against existing data in the table. The logic appears
to be "it's OK to insert UK in the table if it's already there". His
AFTER trigger permits everything. But a BEFORE trigger would have kept
the table empty.


--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.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
May 20 '07 #6
Erland Sommarskog wrote:
DA Morgan (da******@psoug.org) writes:
>>The trigger fires *after* an insert has taken place, therefore in the
second case the trigger rollsback because the country does now indeed
exist in the subquery

Any ideas?

That is one of the major problems with a product that only has AFTER
triggers. In those products that have both BEFORE and AFTER triggers,
AFTER triggers are used for auditing and BEFORE triggers used for
security and integrity. Essentially you are trying to do the right
thing, in the wrong way, in a product that truly doesn't support it.

Actually, SQL Server also has INSTEAD OF triggers, which is not really
the same thing as an BEFORE trigger. Since an INSTEAD OF trigger requires
you to redo the action that trigger it, it less apetizing for checks -
unless the check is of the kind "DELETE is not permitted on this table".

But a BEFORE trigger would not have help Shane, as his trigger seemed to
perform a check against existing data in the table. The logic appears
to be "it's OK to insert UK in the table if it's already there". His
AFTER trigger permits everything. But a BEFORE trigger would have kept
the table empty.

Hi
Yes you are correct, my trigger would keep a new table empty, however this
trigger is being written for an existing table, that has existing entries.
I think the point of my trigger is supposed to keep the country list static.

I have used the following trigger, however I am not happy with it, as the
values are hard-coded.

create trigger chk_team
on teams
for insert as
declare @chkCountry as char(2)
select @chkCountry = (select country from INSERTED)
if @@ROWCOUNT =0 RETURN
If @chkCountry NOT IN ('NZ', 'AU', 'SA')

BEGIN
raiserror('Impossible country entered', 16, 1)
ROLLBACK TRANSACTION
END

--
Q: How can you tell that a mathematician is extroverted?
A: When talking to you, he looks at your shoes instead of at his.

May 20 '07 #7
Shane (sh***@weasel.is-a-geek.net) writes:
Yes you are correct, my trigger would keep a new table empty, however
this trigger is being written for an existing table, that has existing
entries. I think the point of my trigger is supposed to keep the country
list static.

I have used the following trigger, however I am not happy with it, as the
values are hard-coded.
If there is a key in this table, then it is not that tricky:

CREATE TRIGGER no_more_teams ON tbl AFTER INSERT, UPDATE AS
IF EXISTS (SELECT *
FROM inserted i
WHERE NOT EXISTS (SELECT *
FROM tbl
WHERE tbl.teamid <i.teamid
AND tbl.country = i.country))
BEGIN
ROLLBACK TRANSACTION
RAISERROR ('No more countries permitted!', 16, 1)
END

create trigger chk_team
on teams
for insert as
declare @chkCountry as char(2)
select @chkCountry = (select country from INSERTED)
Again: you must not do this. A trigger must be able to handle the
situation more than one row is inserted, so you cannot select into
a variable.

....Wait! Slap me on the face! The trigger above will also not handle
multi-row inserts correctly, but may permit new countries in this case.
OK, so it is a bit more tricker. What about:
IF EXISTS (SELECT *
FROM (SELECT country, COUNT(*) AS cnt
FROM inserted
GROUP BY country) AS i
JOIN (SELECT country, COUNT(*) AS cnt
FROM tbl
GROUP BY country) AS t ON t.country = i.country
WHERE t.cnt = i.cnt)
BEGIN
ROLLBACK TRANSACTION
RAISERROR ('No more countries permitted!', 16, 1)
END

Or write an INSTEAD OF trigger, in which case your original logic
will work. But you still need to handle multi-row inserts.)

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.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
May 20 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Matik | last post by:
Hello to all, I have a small question. I call the SP outer the DB. The procedure deletes some record in table T1. The table T1 has a trigger after delete. This is very importand for me, that...
6
by: Scott CM | last post by:
I have a multi-part question regarding trigger performance. First of all, is there performance gain from issuing the following within a trigger: SELECT PrimaryKeyColumn FROM INSERTED opposed...
9
by: Martin | last post by:
Hello, I'm new with triggers and I can not find any good example on how to do the following: I have two tables WO and PM with the following fields: WO.WONUM, VARCHAR(10) WO.PMNUM,...
6
by: Mary | last post by:
We are developing a DB2 V7 z/OS application which uses a "trigger" table containing numerous triggers - each of which is activated by an UPDATE to a different column of this "trigger" table. When...
0
by: Dave Sisk | last post by:
I've created a system or external trigger on an AS/400 file a.k.a DB2 table. (Note this is an external trigger defined with the ADDPFTRG CL command, not a SQL trigger defined with the CREATE...
0
by: JohnO | last post by:
Thanks to Serge and MarkB for recent tips and suggestions. Ive rolled together a few stored procedures to assist with creating audit triggers automagically. Hope someone finds this as useful as...
1
by: deepdata | last post by:
Hi, I am creating a trigger in DB2 express version. When i use the following syntax to create trigger CREATE TRIGGER USER_PK_TRIGGER BEFORE INSERT On users REFERENCING NEW As N FOR EACH...
9
by: Ots | last post by:
I'm using SQL 2000, which is integrated with a VB.NET 2003 app. I have an Audit trigger that logs changes to tables. I want to apply this trigger to many different tables. It's the same trigger,...
11
by: tracy | last post by:
Hi, I really need help. I run this script and error message appeal as below: drop trigger log_errors_trig; drop trigger log_errors_trig ERROR at line 1: ORA04080: trigger 'LOG_ERRORS-TRIG'...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.