Using "IF EXISITS" with SQL

FlatLine84

[H]ard|Gawd
Joined
Apr 7, 2005
Messages
1,521
I'm currently trying to make one of my queries a little less accident prone. It currently creates a record, but if it's run again would create a duplicate record, I want avoid this. Here is an example:

INSERT INTO Table (Title)
VALUES (New Title)

Could I use some form of IF statement to check first? like...

IF EXISTS (SELECT Title.Table)
GO

I know I've really screwed up how to write this, but am I headed in the right direction? Any help would be awesome.
 
simpler solution, put a unique index on your column.

I'm assuming you are using mssql server
 
IF NOT EXISTS (SELECT Title FROM Table WHERE Title=NewTitle) INSERT INTO Table (Title) VALUES (New Title)
 
I'm using MSDE, I don't think that and index is possible in the situation, as I don't have full control over the database structure... I can only add data to how it's currently setup.
 
thats a very clunky solution, a unique constraint would be the way to go. if your rdbms doesnt support that find another one.
 
Back
Top