在ORDERS表中添加一行,然后增加该产品和客户的订购数量?

时间:2017-09-08 14:48:51

标签: sql-server triggers

我正在尝试学习SQL,虽然到目前为止我的旅程非常成功,但我遇到了触发器的问题。为了记录,我正在使用SQL Server 2016.我将不胜感激任何帮助。如果需要更多详细信息,请与我们联系。

2 个答案:

答案 0 :(得分:-1)

如果您只是在customer表中添加一个已删除的标志,并且在触发器中将刚删除的列更新为true,则会更安全。

但是如果您确实需要在删除父记录后删除子记录,请尝试使用级联删除。你可以参考这篇旧帖子。 How do I use cascade delete with SQL Server?

答案 1 :(得分:-1)

希望它会有所帮助

-------------
--cascade delete way
-------------

CREATE TABLE dbo.customers (
       customer_id INT NOT NULL
     , somedata    UNIQUEIDENTIFIER NOT NULL 
     , CONSTRAINT PK_Customer PRIMARY KEY (customer_id)
     );

CREATE TABLE dbo.orders (
       OrderID     INT NOT NULL
     , customer_id INT NOT NULL
     , somedata    UNIQUEIDENTIFIER NOT NULL 
     , CONSTRAINT PK_Order PRIMARY KEY (OrderID)
     , CONSTRAINT FK_CustomerOrder FOREIGN KEY (customer_id) 
REFERENCES dbo.customers (customer_id) ON DELETE CASCADE
     );

INSERT INTO dbo.customers (customer_id,somedata)
VALUES (1,NEWID()),(2,NEWID())

INSERT INTO dbo.orders(OrderID,customer_id,somedata)
VALUES (1,1,NEWID()),(2,2,NEWID())

DELETE FROM dbo.customers WHERE customer_id = 1

SELECT * FROM dbo.orders

-------------
--trigger way
-------------

CREATE TABLE dbo.customers1 (
       customer_id INT NOT NULL
     , somedata    UNIQUEIDENTIFIER NOT NULL 
     , CONSTRAINT PK_Customer1 PRIMARY KEY (customer_id)
     );

CREATE TABLE dbo.orders1 (
       OrderID     INT NOT NULL
     , customer_id INT NOT NULL
     , somedata    UNIQUEIDENTIFIER NOT NULL 
     , CONSTRAINT PK_Order1 PRIMARY KEY (OrderID)
     , CONSTRAINT FK_CustomerOrder1 FOREIGN KEY (customer_id) 
REFERENCES dbo.customers1 (customer_id) ON DELETE CASCADE
     );

GO

CREATE TRIGGER DELTRIG
ON  dbo.customers1
FOR DELETE
AS
     DELETE C
     FROM dbo.orders1 AS C
        INNER JOIN DELETED ON
            C.customer_id = DELETED.customer_id

GO

INSERT INTO dbo.customers1 (customer_id,somedata)
VALUES (1,NEWID()),(2,NEWID())

INSERT INTO dbo.orders1(OrderID,customer_id,somedata)
VALUES (1,1,NEWID()),(2,2,NEWID())


DELETE FROM dbo.customers1 WHERE customer_id = 1

SELECT * FROM dbo.orders1