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

insert only if entry does not exist?

Status
Not open for further replies.

LucyP

Programmer
Jan 17, 2001
51
ES
I feel like I should know how to do this, but:

I have to write some sql to add an entry to a table. I want the sql to check first that the entry does not exist though and I cannot get this to work.

This is the sql I've been using, but it doesn't work - can anyone tell me what I've missed (I think it's probably the way I've done the if statement - I learned this from a book only this morning)?

SELECT ListName
FROM ListNames
WHERE (ListName = 'SampleListName');
IF @@rowcount = 0
INSERT
INTO ListNames(ListName)
VALUES ('SampleListName')


thanks
 
This should do what you want

IF (select count (Listname) from ListNames where ListName = 'SampleListName') = 0
begin
insert into ListNames(ListName)
values ('SampleListName')
end

Rick.
 
Or you could do this:

IF NOT EXISTS(SELECT ListName FROM ListNames WHERE ListName = 'SampleListName')
BEGIN
INSERT INTO ListNames(ListName)
VALUES('SampleListName')
END

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top