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.
我正在使用VS 2008和SQL Server 2005.问题是,当我插入一个新的记录,这是字符串数据。它继续输入已经在表中退出的相同数据,一次又一次。但我希望我的插入查询运行的地方。我在那里检查它不允许表中的类似数据。
My scenario:
I have to decide on these two string columns: 'source' and 'destination'
我必须决定这两个字符串列:'source'和'destination'
If similar source and destination occur in any record we must stop we the entry on record.
如果在任何记录中出现类似的源和目的地,我们必须停止记录中的条目。
Share the solution.
分享解决方案。
1 个解决方案
#1
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.
最简单的方法是在数据库上放置一个“UNIQUE约束”。然后,每次执行SQL UPDATE或SQL INSERT时,数据库服务器都会检查新SQL操作的有效性,如果它违反了数据完整性约束,则取消它。
For example (copying from this SQL tutorial):
例如(从此SQL教程复制):
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:
如果要在两列上添加UNIQUE约束,可以使用以下语句:
CREATE TABLE Example
(Col1 int NOT NULL,
Col2 int NOT NULL,
UNIQUE (Col1, Col2)
)
Hope I helped!
希望我帮忙!
#1
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.
最简单的方法是在数据库上放置一个“UNIQUE约束”。然后,每次执行SQL UPDATE或SQL INSERT时,数据库服务器都会检查新SQL操作的有效性,如果它违反了数据完整性约束,则取消它。
For example (copying from this SQL tutorial):
例如(从此SQL教程复制):
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:
如果要在两列上添加UNIQUE约束,可以使用以下语句:
CREATE TABLE Example
(Col1 int NOT NULL,
Col2 int NOT NULL,
UNIQUE (Col1, Col2)
)
Hope I helped!
希望我帮忙!