更新值为0时创建触发器

时间:2016-05-22 14:35:10

标签: sql-server

我想在字段s_QuantidadeStock(库存数量)达到0时添加例如30个单位。 如何使用触发器功能执行此操作?

2 个答案:

答案 0 :(得分:1)

CREATE TRIGGER trUpdateQuantityInStock
on tblQuantittyInStock
after UPDATE
AS
begin
;with cte as ( --wrap query into CTE
select id, QInStock from inserted --new rows is here
where QInStock <= 0 -- your condition
)
update trUpdateQuantityInStock
set QInStock = 30
from trUpdateQuantityInStock t --update only rows
inner join cte on t.id = cte.id --where condition meets
end

说明:

此处提供完整说明:https://msdn.microsoft.com/en-us/library/ms189799.aspx
简而言之,插入,更新和删除等DML查询创建了虚拟表inserteddeleted,它们仅在触发器中可用(仅限)。此表的模式与触发器创建的表的模式匹配(在本例中为trUpdateQuantityInStock)。

答案 1 :(得分:0)

试试这可能对你有用

class Entrada(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    medicamento = models.ForeignKey(Medicamento, verbose_name=_(u'Medicamento'))
    serial = models.AutoField(_(u'Serial'), null=False, blank=False, unique=True, db_index=True, primary_key=True)
    validade = models.DateField(_(u'Validade'), auto_now=False, auto_now_add=False)
    lote = models.CharField(_(u'Lote do fabricante'), null=False, blank=False, max_length=20)
    quantidade = models.PositiveIntegerField(_(u'Quantidade'), null=False)
    mud = models.PositiveIntegerField(_(u'Menor unidade de dispensa'), null=False)
    data_entrada = models.DateField(_(u'Data de entrada'), default=timezone.now())