views:

93

answers:

2

I have table that I insert data with following query (from c# code):

INSERT INTO [BazaZarzadzanie].[dbo].[Wycena]
   ([KlienciPortfeleKontaID]
   ,[WycenaData]
   ,[WycenaTyp]
   ,[WycenaWartosc]
   ,[WycenaWaluta]
   ,[WycenaUzytkownik]
   ,[WycenaUzytkownikData])
VALUES
   (@varKlienciPortfeleKontaID
   ,@varWycenaData
   ,@varWycenaTyp
   ,@varWycenaWartosc
   ,@varWycenaWaluta
   ,@varWycenaUzytkownik
   ,@varWycenaUzytkownikData)

Table creation script looks like this:

CREATE TABLE [dbo].[Wycena](
[KlienciPortfeleKontaID] [int] NULL,
[WycenaData] [datetime] NULL,
[WycenaTyp] [int] NULL,
[InID] [int] NULL,
[WycenaIlosc] [decimal](18, 2) NULL,
[WycenaCena] [decimal](18, 2) NULL,
[WycenaWartosc] [decimal](18, 2) NULL,
[WycenaWaluta] [nvarchar](3) NULL,
[WycenaUzytkownik] [nvarchar](50) NULL,
[WycenaUzytkownikData] [datetime] NULL
) ON [PRIMARY]

It also has couple of foreign keys but nothing that i could make primary/unique key. So i thought to prevent duplicates i would go for a trigger since to know one row is duplicate i actually have to test every single value of that row (well maybe not 2 last columns) ? This table has around 2mln rows.

Is this good idea? Or is there a better way?

Below is trigger I've created (not tested if it works):

CREATE TRIGGER [dbo].[trg_WycenaDuplicateCheck]
   ON [dbo].[Wycena] FOR INSERT
AS

IF EXISTS(SELECT INSERTED.[KlienciPortfeleKontaID]
  ,INSERTED.[WycenaData]
  ,INSERTED.[WycenaTyp]
  ,INSERTED.[InID]
  ,INSERTED.[WycenaIlosc]
  ,INSERTED.[WycenaCena]
  ,INSERTED.[WycenaWartosc]
  ,INSERTED.[WycenaWaluta]
  FROM INSERTED, Wycena
  WHERE INSERTED.[KlienciPortfeleKontaID] = Wycena.[KlienciPortfeleKontaID]
  AND INSERTED.[WycenaData] = Wycena.[WycenaData]
  AND INSERTED.[WycenaTyp] = Wycena.[WycenaTyp]
AND INSERTED.[InID] = Wycena.[InID]
  AND INSERTED.[WycenaIlosc] = Wycena.[WycenaIlosc]
    AND INSERTED.[WycenaCena] = Wycena.[WycenaCena]
      AND INSERTED.[WycenaWartosc] = Wycena.[WycenaWartosc]
  AND INSERTED.[WycenaWaluta] = Wycena.[WycenaWaluta]
  Group By INSERTED.[KlienciPortfeleKontaID]
  ,INSERTED.[WycenaData]
  ,INSERTED.[WycenaTyp]
  ,INSERTED.[InID]
  ,INSERTED.[WycenaIlosc]
  ,INSERTED.[WycenaCena]
  ,INSERTED.[WycenaWartosc]
  ,INSERTED.[WycenaWaluta]
  HAVING COUNT (*) > 1)

BEGIN
RAISERROR('>>>DUPLICATES PREVENTED<<< ',10,1)
ROLLBACK TRAN
END
+7  A: 

Create a "unique" index on the fields you care about.

CREATE UNIQUE INDEX IX_YOUR_FAVORITE_NAME
  ON [dbo].[Wycena](... list of columns goes here ...)
Pointy
They are unique if all are checked at same time? Will this handle it?
MadBoy
Uhh... I don't know exactly what you're asking. When you create a unique index on multiple fields, the database server will not let you create a new record if the fields in the new record all match an old record already recorded in the index.
Pointy
That's what i wanted to know. Thanks
MadBoy
+1  A: 

Seems like you need to look at UNIQUE Constraints

astander