T
T
thechemis2016-12-08 15:42:44
SQL
thechemis, 2016-12-08 15:42:44

How to make a trigger that will not allow duplicate data?

Good evening! It is necessary to add a unique string for any field.
I write like this:

alter trigger Triger1
on Week_Schedule for insert
as
  if @@ROWCOUNT=1
begin
  if exists (
    select *
    from inserted as i, Week_Schedule as w
    where i.Week_Number = w.Week_Number 
  )
  begin
    rollback tran
  print
    'Неделя с таким номером уже существует!'
  end
end

but something goes wrong. When adding even a unique line, a warning pops up with the text of my trigger. How can I fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Tsvetkov, 2016-12-08
@tsklab

It is necessary to add a unique string for any field.
This is not done by a trigger, but by a constraint (unique index or CONSTRAINT).

A
Artyom Karetnikov, 2016-12-11
@art_karetnikov

1. by the type of trigger has already been said. Otherwise, the wrong thing is that the string has already been added at the time of the check and, of course, exists always works correctly.
2. The trigger is executed for each row (that's why the uniqueness does not need to be checked), hence @rowcount = 1 is useless.
3. The trigger is needed not on insert, but on insert, update

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question