473,653 Members | 3,000 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with Triggers

I'm trying my hand at triggers and it doesn't seem to be working for me. I
have a very simple database that consists of one table: Employees. I want
to create a trigger that will limit the EMP_TITLE field to either Ms., Mr.,
or Mrs. I am using the following code:

CREATE trigger triTitleCheck
ON employee
FOR insert, update
AS
declare @v1 varchar
SELECT @v1 = inserted.emp_ti tle FROM inserted

if @v1 <> 'Mr.' and @v1 <> 'Mrs.' and @v1 <> 'Ms.'

BEGIN
rollback transaction
raiserror( 'Title must be one of the following: Mr., Ms., or
Mrs.', 16, 10 )
END

It is generating the error for ANY data, even if I do enter one of the three
legal values. Any help?

-- Curtis

Jul 20 '05 #1
3 1762
On Thu, 4 Nov 2004 22:37:23 -0600, Curtis Gilchrist wrote:
I'm trying my hand at triggers and it doesn't seem to be working for me. I
have a very simple database that consists of one table: Employees. I want
to create a trigger that will limit the EMP_TITLE field to either Ms., Mr.,
or Mrs. I am using the following code:

CREATE trigger triTitleCheck
ON employee
FOR insert, update
AS
declare @v1 varchar
SELECT @v1 = inserted.emp_ti tle FROM inserted

if @v1 <> 'Mr.' and @v1 <> 'Mrs.' and @v1 <> 'Ms.'

BEGIN
rollback transaction
raiserror( 'Title must be one of the following: Mr., Ms., or
Mrs.', 16, 10 )
END

It is generating the error for ANY data, even if I do enter one of the three
legal values. Any help?

-- Curtis


Hi Curtis,

First, limiting data to a set of legal values is not a task for a trigger.
You use a CHECK constraint if the set of legal values is fairly short and
stable, or a FOREIGN KEY constraint to a lookup table if the list is long
and need to be changed relatively often.

Examples, assuming the titles are stable and the list of valid department
is subject to change:

CREATE TABLE Employees (Emp_No int NOT NULL,
Title char(4) NOT NULL,
Dept_No int NOT NULL,
PRIMARY KEY (Emp_No),
CHECK (Title IN 'Mr.', 'Mrs.', 'Ms.'),
FOREIGN KEY (Dept_No) REFERENCES Departments
)
Now, assuming you attempt to use a trigger just to get some exercise,
there are two errors in your trigger code. The first is the declaration of
@v1. Since you didn't specify a length, SQL Server assumes varchar(1);
after the assignment
SELECT @v1 = inserted.emp_ti tle FROM inserted
the value of @v1 will be truncated to 'M' if the row inserted has a legal
value. Since 'M' is not equal to 'Mr.', 'Mrs.' or 'Ms.', the transaction
is rolled back and the error is raised.

The last problem with your trigger is that it doesn't handle multi-row or
zero-row updates or inserts. Remember that a trigger is fired exactly once
per insert, update or delete statement; all rows affected by the trigger
will be in the inserted and/or deleted pseudo-tables. Your current trigger
will check just one of the rows (and it's hard to predict exactly which
one), so you'll still be able to load erroneous data! Also, your trigger
will raise an error (even after correcting the @v1 declaration) if you
write something like
UPDATE Employees
SET Title = 'Mr.'
WHERE Emp_No <> Emp_No
(which will of course affect no row at all)

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #2
Hugo Kornelis (hugo@pe_NO_rFa ct.in_SPAM_fo) writes:
Also, your trigger will raise an error (even after correcting the @v1
declaration) if you write something like
UPDATE Employees
SET Title = 'Mr.'
WHERE Emp_No <> Emp_No
(which will of course affect no row at all)


That would only cause an error to be raised if ANSI_NULLS is off, which
it shouldn't be.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #3
On Fri, 5 Nov 2004 22:41:37 +0000 (UTC), Erland Sommarskog wrote:
Hugo Kornelis (hugo@pe_NO_rFa ct.in_SPAM_fo) writes:
Also, your trigger will raise an error (even after correcting the @v1
declaration) if you write something like
UPDATE Employees
SET Title = 'Mr.'
WHERE Emp_No <> Emp_No
(which will of course affect no row at all)


That would only cause an error to be raised if ANSI_NULLS is off, which
it shouldn't be.


Hi Erland,

Woops! You're right. Thanks for the catch!

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #4

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

Similar topics

4
2530
by: Mark Flippin | last post by:
I'm just starting to use triggers in my databases and find the support in Enterpise Manager lacking. Using Enterprise Manager and Query Analyzer you can maintain the triggers, but it's cumbersome. Are there better tools for creating and managing triggers? Mark Flippin
11
2262
by: William Payne | last post by:
Ok, in my program I have a std::list<Document*>, where Document is one of my own classes. I need to go through this list and check each item if it's ready for deletion. If it's not, skip to next, if it's ready I take steps to delete it. The thing is that the list is part of a gui application and the system removes the Document* from the list during the execution of the loop body. That means I cant use iterators to iterate over the list....
1
1823
by: tim.pascoe | last post by:
I'm trying to generate scrips for a database, and everything so far has worked fine, except for the triggers. When I try and script existing triggers, all I get is a blank file - no SQL script. I tried single files for each object, all in one file, triggers only, the entire database. I can't figure it out, but I know the triggers are there. Any suggestions, or am I missing something undocumented in SQL-Server 2000?
4
2713
by: stacdab | last post by:
We have a partitioned view with 4 underlying tables. The view and each of the underlying tables are in seperate databases on the same server. Inserts and deletes on the view work fine. We then add insert and delete triggers to each of the underlying tables. The triggers modify a different set of tables in the same database as the view (different than the underlying table). The problem is those triggers aren't fired when inserting or...
4
1955
by: SUKRU | last post by:
Hello everybody. Unfortunately I am pretty new to sql-server 2000 I need some help with a Trigger I created. I created a trigger witch takes the id of the affected row and does a update on a other table with that ID. The trigger works fine with one affected row. But when there are more then one rows affected, i get an error. I found out that SQL-server does not support row-level triggers. I should probable make my own cursor and...
1
1451
by: nDaKota | last post by:
I am current converting PowerBuilder to C#. Now I'm having problem on triggers. I understand what a triggers does. The problem is what happens if a trigger is being triggered? Example: I execute a trigger say "trigger A"so the current process executed in the queue is paused. Then i issue another trigger "trigger B". Scenario 1: Considering the two triggers are not related. Upon issuing trigger B should trigger A be paused? Or Is it...
0
8313
debasisdas
by: debasisdas | last post by:
trigger sample code Ex#10 ======================= INSTEAD OF TRIGGER ---------------------------------------- create or replace trigger mytrig instead of delete or insert or update on eview declare a number(2); begin
3
2848
by: jenipriya | last post by:
Tables ------------ Employee (EmpID, EmpName,DeptID DateOfJoin, Sal, Addr) Finance (EmpID, Sal) Club (Clubname, EmpID, Fee, DateOfJoin) Leave (EmpID, Date) Department (DeptID, DeptName, NoOfEmployees)
0
4489
debasisdas
by: debasisdas | last post by:
This thread contains some useful tips/sample codes regarding TRIGGERS in oracle, that the forum members may find useful. TRIGGERS: =============== Database trigger is a PL/SQL block that is executed on an event in the database. The event is related to a particular data manipulation of a table such as inserting, deleting or updating a row of a table. Triggers may be used : 1.To implement complex business rule, which cannot be...
4
5732
by: --CELKO-- | last post by:
I need to convert a bunch of DB2 triggers to Oracle. Is there any kind of tools for this?
0
8370
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8283
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
8811
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
8704
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
8470
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
7302
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
6160
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...
0
4291
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2707
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

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.