-2

I am using VS 2008 and SQL Server 2005. And the problem is that when I insert a new record which is string data. It continues on entering the same data which is already exiting in the table, again and again. But I want that where my insert query is running. I place the check there that it does not allow similar data in the table.

My scenario:

I have to decide on these two string columns: 'source' and 'destination'

If similar source and destination occur in any record we must stop we the entry on record.

Share the solution.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
TalhaDX
  • 1
  • 5

1 Answers1

0

The easiest way to do it is by putting a 'UNIQUE constraint' on your database. Then, each time an SQL UPDATE or an SQL INSERT is executed, the database server would check the validity of the new SQL action and cancel it if it violates your data integrity constraing.

For example (copying from this SQL tutorial):

CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

If you want to add a UNIQUE constraint on two columns, you could use such a statement:

CREATE TABLE Example
(Col1 int NOT NULL,
Col2 int NOT NULL,
UNIQUE (Col1, Col2)
)

Hope I helped!

Pantelis Natsiavas
  • 5,293
  • 5
  • 21
  • 36