473,734 Members | 2,511 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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('Impo ssible 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 3310
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('Impo ssible 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('Impo ssible 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_CheckC ountry ON teams
FOR INSERT, UPDATE
AS
IF @@ROWCOUNT>0 AND UPDATE(CountryC ode) 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_Ch eckTeams 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.wash ington.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****@sommarsk og.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('Impo ssible 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.i s-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****@sommarsk og.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
2003
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 the SP will be finished ASAP, that's why, I do not want, and I do not need to wait for a trigger.
6
6555
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 to: SELECT * FROM INSERTED
9
3457
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, VARCHAR(10) WO.PROBLEMCODE, VARCHAR(8)
6
7143
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 the triggers are fired, various other operations are performed on other tables in the database. The triggers are not created on these other tables because other programs perform updates to these tables and we do not want the triggers to fire...
0
7146
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 TRIGGER statement.) I've also defined a SQL stored proc, and the trigger is set to call this SP. I've posted the simplified source below. I can manually call the stored proc, and the external trigger is created without any errors. However, when I do...
0
2477
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 I've found it educational. Note: - I build this for use in a JDEdwards OneWorld environment. I'm not sure how generic others find it but it should be fairly generic. - I use a C stored procedure GETJOBNAME to get some extra audit data,
1
2212
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 ROW
9
9310
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, with the exception of the table name. I could manually change the table name in the trigger and create it, over and over, but I'd like to automate this - by iterating through the collection of tables and passing the tablename to something that...
11
7876
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' does not exist drop table log_errors_tab;
0
8776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9449
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9182
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectóplanning, coding, testing, and deploymentówithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Duprť who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.