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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search for duplicates before doing INSERT

Status
Not open for further replies.

avu

Technical User
Aug 8, 2003
53
CA
Hello,

Can anyone advice if it's possible to insert a record (name + address) into a table where it would search the table first for duplicate 'name' or 'address'?

I normally run 2 procedures in which first procedure searching for duplicate. If it's empty, then call 2nd procedure to do the INSERT.

Can this be done in one procedure or sql statement?

Thanks much in advance.

Allan
 
Yes, somewhat like

Code:
if not exists (select * from t
where adress = @adress ...  )
begin
   insert into t ...
   set @e = @@error
   if @e <> 0 goto errorLabel
end

is one way.
 
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tmp_testaddress]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
CREATE TABLE [dbo].[tmp_testaddress] (
[ts_pk] [int] IDENTITY (1, 1) NOT NULL ,
[ts_name] [char] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[ts_address] [char] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
end
GO

declare @L_cname char(64), @l_caddress char(128)
set @L_cname = 'Joe Person'
set @l_caddress = '144 Main St.'

if not exists(select ts_pk from tmp_testaddress where ts_name = @l_cname and ts_address = @l_caddress)
begin
insert into tmp_testaddress(ts_name, ts_address)
VALUES(@l_cname,@l_caddress)
end

select * from tmp_testaddress

Change the values of @l_cname and @l-caddress (or not) to demonstrate.

HTH,

Phil Hegedusich
Senior Web Developer
IIMAK
-----------
Boy howdy, my Liberal Studies degree really prepared me for this....
 
Thanks both of you very much for your help.

Best regards.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top