我想在SQL Server 2012中创建一个触发器,当我在特定表中插入一行时激活该触发器。
触发器必须在特定列中插入一个值,在我插入新行的同一个表和行中。
只有当我插入的行中的特定列没有值时,才能激活触发器。空。
让我们说我插入:
car
car_make | car_price | car_img
如果我在插入中提供所有值:
car_make | car_price | car_img
触发器不得激活
但是,如果我只插入2列的值:
car_make | car_price
car_img
值为null,然后触发器必须激活并执行以下操作:
car_img
列中插入预定义值
PS。我必须使用触发器,它用于作业。我不能使用默认值。
答案 0 :(得分:1)
Create Trigger tr_ForInserts_car
ON dbo.car
FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
UPDATE Car
SET car_make = /*Your Default Value*/
WHERE car_make IS NULL
UPDATE Car
SET car_price = /*Your Default Value*/
WHERE car_price IS NULL
UPDATE Car
SET car_img = /*Your Default Value*/
WHERE car_img IS NULL
END
修改强>
我以前的建议会更新相应列为空的所有行,只更新新插入行的列,请尝试以下内容
Create Trigger tr_ForInserts_car
ON dbo.car
FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
UPDATE Car
SET Car.car_make = /*Your Default Value*/
FROM Car INNER JOIN inserted
ON Car.PrimaryKey = inserted.PrimaryKey
WHERE Car.car_make IS NULL
UPDATE Car
SET Car.car_price = /*Your Default Value*/
FROM Car INNER JOIN inserted
ON Car.PrimaryKey = inserted.PrimaryKey
WHERE Car.car_price IS NULL
UPDATE Car
SET Car.car_img = /*Your Default Value*/
FROM Car INNER JOIN inserted
ON Car.PrimaryKey = inserted.PrimaryKey
WHERE Car.car_img IS NULL
END