0

I have a table with columns CompanyID, EmployeeCode. EmployeeCode is unique and CompanyID can be repeated. So we can keep a list of employees in Google, Apple etc.

I want a way to ensure that the same employee cannot be added if he/she is already in the database. What would be a good way to do this ? I'd prefer not to create additional columns or tables for this.

6
  • Before insert get the count using select query with where condition depending on result you can allow to insert. Commented Dec 6, 2013 at 6:41
  • The better way to insert using STOREPROCEDURE Commented Dec 6, 2013 at 6:43
  • On top of @Praveen's suggestion - you can add an unique index on the values that makes the entity unique and then the database will complain if you really try to enter the same values once more. Commented Dec 6, 2013 at 6:53
  • @AllanS.Hansen - Please explain what you mean. Commented Dec 6, 2013 at 6:55
  • 2
    @Trojan If you add a unique index on the relevant fields, the database engine will not allow you to insert duplicate records. Commented Dec 6, 2013 at 7:07

3 Answers 3

4

Create a UNIQUE constraint on the column where you want to prevent duplicates:

CREATE UNIQUE INDEX [IX_YourTableName_EmployeeCode] ON [YourTableName] (EmployeeCode)
Sign up to request clarification or add additional context in comments.

2 Comments

Will this work in this case - If I want the combination of two columns to be considered unique ? Ex. Number, Name. We have rows (1, Jon), (2, David), (3, Penny). Its okay if we insert (1, smith) or (7, Jon), but NOT (1,Jon)
@Trojan.ZBOT Yes, you can enforce the constraint across multiple columns. This is called a "composite" index. Just include the list of column names separated by commas. Example: CREATE UNIQUE INDEX ... (column1, column2, column3)
0

Try this..

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

Comments

0

Try this

    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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.