user240141
user240141

Reputation:

How to check for duplicate records in table while inserting and updating

I need to check for duplicate records in my table while insert and update. Below is my query. It works fine in case of insert, but fails at update. I am unable to figure that out. Please help me.

Insert:

Set @Count =  (Select ISNULL(Count(*),0) From AccountMaster Where [Name] = @Name and Id=@Id and Flag=1);
If @Count >0 and @InsertUpdateFlag=1
  BEGIN
    Set @DbErrormessage = 'Business Name and Account Id must be unique. Try again.';
  END   

Update :

Set @Count =  (Select Count(*) From AccountMaster Where [Name] = @Name and Id <> @Id and Flag=1);
 If @Count >0 and @InsertUpdateFlag=2
  BEGIN
   Set @DbErrormessage = 'Business Name is in already in use by some other account. Try another one.';
  END

The condition of update is that the Id and Name must not exist in the database. So I am taking count where name doesnot exists with any other id. But it seems , not working.

Below is my table schema.

SELECT [PkId] //Primary Key as Int
      ,[Id]  // Unique Key varchar(25)
      ,[Created]
      ,[Type]
      ,[Status]
      ,[Name]  //Business Name
      ,[ContactPerson]
      ,[ContactNumber]
      ,[Email]
      ,[Address]
      ,[LocationId]
      ,[Remarks]
      ,[Flag]
  FROM [AccountMaster]

Id and Business Name must be unique while both insert/update. So I need to check it while insert and update.

Upvotes: 0

Views: 866

Answers (1)

Wencesbc
Wencesbc

Reputation: 116

Put the Unique constraint in the name and forget the checks, you can handle the Constraint violation and then you know the name already exists

Upvotes: 1

Related Questions