473,796 Members | 2,619 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

what type of Constraint to prevent duplicates

I am trying to either write a trigger or a check constraint to prevent
duplicates in my table. There are two columns I need to look at for the
duplicates and only one combo value for both columns is allowed in the
table. For e.g.
Column Serial can have only one '123456' value with testresult value as
'PASS'. This serial can be in the table many times with any other combo
so for e.g.
The table could contain 100 entries for serial column value '123456'
with testresult value 'FAIL', 'PENDING' etc.

** TESTED SCHEMA BELOW **

-- create table
CREATE TABLE bstresult
(ID int IDENTITY (1, 1) NOT NULL ,
serial char (10) NULL ,
testresult char (10) NULL
)
-- Insert valid values
insert into bstresult values ('123456','PASS ')
insert into bstresult values ('123456','FAIL ')
insert into bstresult values ('123456','FAIL ')
insert into bstresult values ('123456','PEND ING')

-- insert invalid value this should fail

insert into bstresult values ('123456','PASS ')

If I simply create a unique constraint on both columns it will not
allow the FAIL combo or PENDING combo with the same serial which I need
to allow.

Appreciate your help.

Jul 23 '05 #1
3 3072
Hi
For this you can create a composite primary key or this can be done by
using INSTEAD OF INSERT Trigger
something like this:

CREATE TRIGGER <TriggerName>
INSTEAD OF INSERT
AS
BEGIN

IF NOT EXISTS(SELECT * FROM bstresult INNER JOIN INSERTED ON
INSERTED.serial = bstresult.seria l AND INSERTED.testre sult =
bstresult.testr esult)
INSERT INTO bstresult SELECT * from INSERTED

END

please let me know if it worked.

best Regards,
Chandra
http://groups.msn.com/SQLResource/
http://chanduas.blogspot.com/
---------------------------------------

*** Sent via Developersdex http://www.developersdex.com ***
Jul 23 '05 #2
[posted and mailed, please reply in news]

(kj****@hotmail .com) writes:
If I simply create a unique constraint on both columns it will not
allow the FAIL combo or PENDING combo with the same serial which I need
to allow.


Here are a couple of variations. You can use an indexed view:

CREATE VIEW showstopper WITH SCHEMABINDING AS
SELECT serial FROM dbo.bstresult WHERE testresult = 'PASS'
go
CREATE UNIQUE CLUSTERED INDEX xyz ON showstopper(ser ial)

You can use an indexed computed column:

CREATE TABLE bstresult
(ID int IDENTITY (1, 1) NOT NULL ,
serial char (10) NULL ,
testresult char (10) NULL,
pass AS CASE testresult
WHEN 'PASS' THEN serial
ELSE convert(varchar , ID)
END CONSTRAINT u_pass UNIQUE(pass)
)

Both this methods requires that you have the settings ANSI_WARNINGS,
CONCAT_NULL_YIE LDS_NULL, ARITHABORT, ANSI_NULLS, QUOTED_IDENTIFI ER
and ANSI_PADDING on. Of these, the settings of ANSI_NULLS and
QUOTED_IDENFIFI ER are stored with stored procecures, and the setting
of ANSI_PADDING is stored with the table column. These settings are
on by default when you connect with local API, except for ARITHABORT,
which you need to set on.

Yet a method is to use a trigger:

CREATE TRIGGER unique_pass ON bstresult FOR INSERT, UPDATE AS
IF EXISTS (SELECT b.serial
FROM inserted i
JOIN bstresult b ON i.serial = b.serial
AND i.testresult = b.testresult
AND i.ID <> b.ID
WHERE i.testresult = 'PASS')

BEGIN
ROLLBACK TRANSACTION
RAISERROR('Atte mpt to insert duplicate PASS record', 16, 1)
END

The INSTEAD OF trigger Chandra posted permits you ignore the duplicate
rather than raising an error. Unfortunately, this approach is somewhat
problematic, since it does not handle multi-rows insert well. If you
insert many rows, and one is a duplicate, all rows are dropped on the
floor. On the other hand, if you insert two duplicate rows, but that
serial are not in the table, both rows make into the table.
--
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 23 '05 #3
On 8 Jun 2005 18:39:26 -0700, kj****@hotmail. com wrote:

(snip)
If I simply create a unique constraint on both columns it will not
allow the FAIL combo or PENDING combo with the same serial which I need
to allow.


Hi kjaggi,

You could use an indexed view for this. I'm typing this example from the
top of my head, so I might have the syntax wrong!

CREATE VIEW FailedResults WITH SCHEMABINDING
AS SELECT serial
FROM dbo.bstresult
WHERE testresult = 'PASS'
go
CREATE UNIQUE CLUSTERED INDEX ix_FailedResult s
ON dbo.FailedResul ts(serial)
go
Best, Hugo
--

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

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

Similar topics

0
1739
by: Morten Gulbrandsen | last post by:
Dear MySQL developers, Could some experienced Database developer please take a look at this ? It is supposed to be plain SQL2. How can it be coded under MySQL Especially all referential triggered actions.
0
650
by: Morten Gulbrandsen | last post by:
Hi Programmers, after this legal statement ALTER TABLE EMPLOYEE TYPE =3D InnoDB; I get=20 Warnings: 0 =20 and still MySQL claims to have to use Type =3D MyISAM,
112
10369
by: Andy | last post by:
Hi All! We are doing new development for SQL Server 2000 and also moving from SQL 7.0 to SQL Server 2000. What are cons and pros for using IDENTITY property as PK in SQL SERVER 2000? Please, share your experience in using IDENTITY as PK .
1
1001
by: Ron | last post by:
I posted this to 'questions' yesterday instead of 'general' by mistake. Sorry if anyone received duplicates. ---------------------------------------------------- Mandatories: Ver 7.3.4, Redhat Linux 8.0, P4, 2GB RAM I want to add a 'nullable' foreign key to a column in a table. I have tables "company" and "project" which may be related by company.companyID <-> project.companyID. project.companyID is allowed to be null. However, when...
10
14705
by: Laurence | last post by:
Hi there, How to differentiate between unique constraint and unique index? These are very similar but I cannot differentiate them? Could someone give me a hand? Thanks in advance
92
6261
by: Heinrich Pumpernickel | last post by:
what does this warning mean ? #include <stdio.h> int main() { long l = 100; printf("l is %li\n", l * 10L);
2
33710
by: Sam Bendayan | last post by:
Greetings, What is the point of Microsoft defining a ROWGUIDCOL property that can be attached to a 'uniqueidentifier' column? This is defined as a column that is 'globally unique', but doesn't the uniqueidentifier datatype already guarantee that? To make matters more confusing, they tell you in Books Online to add a Unique constraint because ROWGUIDCOL does not guarantee uniqueness...so what's the point? Apparently the only...
25
2371
by: Thomas R. Hummel | last post by:
I'm going to try to describe this situation as best as I can, but if anything is unclear please let me know. Some of this database was already in place before I arrived on the scene, and I don't really have the buyin to change it. There is a table of certificates that a person can hold. A person may hold certificates of various types. I need to further group a person's certificates together so that (for example) renewal dates can be...
11
4098
beacon
by: beacon | last post by:
Hi everybody, I created a database that links one table from an ODBC data source. I saved my password and UID to the data source so neither myself nor anyone else would have to login each time (that's just bonus background info). I take this table, which is read-only, and run an APPEND query that adds new items from the table into another table I created (that has two additional fields that will be updated by the user via a form). I also...
0
9685
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
9533
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
10461
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
10019
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
9057
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
7555
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
6796
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2928
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.