I am in the consecutive 1070039332 , as seen in the image. But I can't let it get past consecutive 1070039400 , I don't have much experience with triggers.
Code:
create trigger restrinccion on [dbo].[tblencfacturas] for update
as
declare @ consecutivo int
select @consecutivo = count(tblencfacturas.consecutivo)
from tblencfacturas
if (@consecutivo>=1070039400) begin
print 'No se puede realizar la Factura, restrinccion sistemas.'
end
The problem is that the
print
on error does not raise any exception, therefore the transaction can be executed without problems. What you should do is raise an error usingRAISEERROR
For example:
Details:
These two parameters can be useful if errors are eventually captured to have finer control over them.
Additional notes
I modified your code, since I understand that what you are looking for is to know if you are trying to add a value of
consecutivo
greater than a limit, what you were doing,select @consecutivo = count(tblencfacturas.consecutivo) from tblencfacturas
was not going to work:consecutivo
For the last point, there are in the triggers, pseudo tables
INSERTED
orDELETED
, with the first one we obtain the rows with the values that we are going to update. So we can do:With what we obtain the largest value
consecutivo
that we want to update or insert, we must take into account that a trigger is executed at the batch level, so you can either update one row or multiple, the previous statement is consistent with any of these forms.As Lamak points out, in MSSQL there is no instance
BEFORE UPDATE
for a trigger, therefore the update will always be performed, the error is an event after this. Therefore, whenever you want to handle a disabling trigger you should handle a transaction and much better a blockTRY .. CATCH ..
, in which case theRAISEERROR
entire transaction can be caught and thrown away. In your example, for the trigger to work as you expect it to, you would do something like this: