I've got a table with hit statistics for many products in another table.

This table is determined such as this

ID (Primary key)
ItemId (Foreign key)
Date
Hits

Giving me possess a record pr. item pr day.

The database can be used inside a multithreaded atmosphere, so two customers will make the very first hit simultaneously leading to two records to become produced, where I would like only one with hits=2. (due to a distinctive index I'd have an exception rather)

How do you make sure that I have only one record pr. item pr. day?

Unique indexes works. That will only allow just one record. Alternatively, you can setup in code a lock, look for the presence of an archive with this ID, when the record is available steer clear of the place and inform the customers from the problem. But when null, then you definitely proceed using the place.

EDIT: A lock might be setup as:

public static object _lock = new object();

public void Save(..)
{
   lock(_lock) {
      //check for existence of an ID
      //process accordingly
   }
}

It's frequently suggested to complete the check both pre and post the lock, because when the lock is launched, an earlier user might have saved the record, but you might also need to be worried about database performance here, so perhaps just doing the work within the lock is alright... you might also need to keep yourself informed this holds up other customers attempting to save the record in the lock point and may modify the performance of the application when the database is slow... something you will have to understand.

HTH.

One method to handle this really is through the index you create in SQL Server. With SQL Server, you may create a distinctive Index but rather than getting it throw the best whenever you make an effort to give a duplicate, it really ignores the duplicate. To get this done, make certain the index type is 'Index' and hang 'Ignore Duplicate Keys' to 'Yes'

CREATE UNIQUE NONCLUSTERED INDEX IX_MyIndex ON MyTable
(
   MyColumn
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = ON, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO