Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

recognizing duplicate record

Status
Not open for further replies.

tek1ket

MIS
Jan 25, 2009
70
IR
how is it possible to prevent inserting a record when it has a duplicate field in it
 
You can use Stored Procedure for your inserts and verify if the value you want to insert already exists before inserting and Raiserror in case it exists.

In SQL Server 2008 you can also take a look into the new MERGE command.
 
it is not primary key
is it possible ti give me an example for that?
 
There's probably lot's of ways to do it. Here's a simple version:

Code:
Create table #TestIT(No_Key varchar(6))
Insert into #TestIt(No_Key) Values('Value1')
Insert into #TestIt(No_Key) Values('Value2')
Insert into #TestIt(No_Key) Values('Value3')

If not Exists (select No_Key from #TestIt  where No_Key = 'Value4')
    Insert into #TestIt(No_Key) Values('Value4')
else Select 'Duplicate key - No Insert'

If not Exists (select No_Key from #TestIt  where No_Key = 'Value4')
    Insert into #TestIt(No_Key) Values('Value4')
else Select 'Duplicate key - No Insert'

Select * from #TestIt

Drop table #TestIt
 
i don't understand, tyson, why you would want to write code for something that the database system offers straight outta da box -- a UNIQUE index

:)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
r937,

I wouldn't and never have. I prefer identity columns. I was answering what I thought the OP asked. Preventing duplicates on a non-key column.
 
you can prevent duplicates in a non-PK column with a UNIQUE index

of course, i suppose you might say that creating a UNIQUE index on a column makes it a key, but that's really just a quibble

:)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
What if you need combination of multiple columns to be unique?
 
a combination of columns may have a UNIQUE index

this is readily apparent if you look up CREATE INDEX in da manual

;-)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Good point, but by the funny coincedence (and this is happening too often) the same question was just asked on another forum I visit, so I got the exact command without even checking the help.
 
Weird.

-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
In my practice it happens all the time. May be because I visit too many forums :)
 
Exact command? what are they talking about? Is that what we call socializing and shouldn't be taken to mean anything?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top