防止插入重复项

时间:2013-12-06 06:34:09

标签: sql sql-server

我有一个包含CompanyID,EmployeeCode列的表。 EmployeeCode是唯一的,可以重复CompanyID。因此,我们可以在Google,Apple等中保留员工名单。

我想要一种方法来确保如果他/她已经在数据库中,则无法添加相同的员工。这样做有什么好办法?我不想为此创建额外的列或表。

3 个答案:

答案 0 :(得分:4)

在要防止重复的列上创建UNIQUE约束:

CREATE UNIQUE INDEX [IX_YourTableName_EmployeeCode] ON [YourTableName] (EmployeeCode)

答案 1 :(得分:0)

试试这个..

Create table UniqueTable
(
CompanyID int, 
EmployeeCode int 
)

--Insert dummy data
INSERT INTO UniqueTable(EmployeeCode ,CompanyID ) Values(1,200)

--When are Going to insert duplicate Ecmployeecode '1' then it will not insert data into table
INSERT INTO UniqueTable(EmployeeCode ,CompanyID ) 
Select 1,200 From  UniqueTable t1
Left join UniqueTable t2 on 1=t2.EmployeeCode
WHERE t2.EmployeeCode  IS NULL


--We are Going to insert different Ecmployeecode '2' it will insert into table
INSERT INTO UniqueTable(EmployeeCode ,CompanyID ) 
Select 2,300 From  UniqueTable t1
Left join UniqueTable t2 on 2=t2.EmployeeCode
WHERE t2.EmployeeCode  IS NULL

答案 2 :(得分:0)

试试这个

    Create PROCEDURE [dbo].[sp_Emp_Insert]
    @EmployeeCode nvarchar(50)
    As
  Begin
  if Not Exists (select EmployeeCode from YOUR_TABlE where EmployeeCode =@EmployeeCode )
  Begin
      Insert QUERY
   End 
  else
  Return 0  
 End  

    End