删除不存在的地方

时间:2018-12-04 16:12:37

标签: tsql sql-delete exists

我在存储过程的DELETE语句中使用NOT EXISTS,并且不存在不存在于数据中。

使用以下示例数据:

CREATE TABLE Region
(
    RegionID INT IDENTITY(1,1)
    ,RegionName VARCHAR(25)
)

GO

INSERT INTO Region(RegionName)
VALUES ('East Coast')
    ,('Mid West')
    ,('West Coast')

GO

CREATE TABLE Customer
(
    CustomerID INT IDENTITY(1,1)
    ,FirstName VARCHAR(5)
    ,Region INT
)

GO 

INSERT INTO Customer(FirstName,Region)
VALUES('Tom',1)
    ,('Mike',2)
    ,('Jean',3)

GO

CREATE TABLE Orders
(
    OrderID INT IDENTITY(1,1)
    ,CustomerID INT
    ,OrderAmount INT
    ,OrderDate DATE
)

GO 

INSERT INTO Orders(CustomerID,OrderAmount,OrderDate)
VALUES(1,10,'2018-11-30')
    ,(2,12,'2018-11-30')
    ,(2,15,'2018-12-01')
    ,(2,8,'2018-12-02')
    ,(2,11,'2018-12-03')
    ,(3,13,'2018-12-01')
    ,(3,20,'2018-12-03')

GO

使用这些数据,我试图创建一个执行以下操作的过程:

CREATE PROCEDURE udsp_GetOrdersOfXAmount @OrderAmount INT, @RegionID INT = 0
AS
BEGIN

DECLARE @ProcedureTemp TABLE
(
    OrderID INT
    ,CustomerID INT
    ,OrderAmount INT
    ,OrderDate DATE
)

INSERT INTO @ProcedureTemp(OrderID,CustomerID,OrderAmount,OrderDate)
SELECT * FROM Orders WHERE OrderAmount >= @OrderAmount

--Do several other UPDATES/ DELETES to @ProcedureTemp

--This is where the issue lies
IF @RegionID > 0 
BEGIN
    DELETE T FROM @ProcedureTemp T
    WHERE NOT EXISTS
        (
            SELECT *
            FROM Customer C
                JOIN @ProcedureTemp T ON T.CustomerID = C.CustomerID
            WHERE C.Region = @RegionID
        )
END

SELECT * FROM @ProcedureTemp

END

GO

如果在使用@RegionID参数填充的情况下执行该过程,则会看到该过程未遵循按区域进行过滤。

E.G。

EXEC udsp_GetOrdersOfXAmount 10,3

但是,如果将DELETE语句中使用的子查询作为其自己的查询运行,则会看到提供的WHERE子句逻辑正在运行。我不明白为什么将它与DELETE语句中的NOT EXISTS一起使用时不起作用。

DECLARE @OrderAmount INT = 10, @RegionID INT = 3

DECLARE @ProcedureTemp TABLE
(
    OrderID INT
    ,CustomerID INT
    ,OrderAmount INT
    ,OrderDate DATE
)

INSERT INTO @ProcedureTemp(OrderID,CustomerID,OrderAmount,OrderDate)
SELECT * FROM Orders WHERE OrderAmount >= @OrderAmount

SELECT *
FROM Customer C
    JOIN @ProcedureTemp T ON T.CustomerID = C.CustomerID
WHERE C.Region = @RegionID

在此先感谢您提供的帮助。

1 个答案:

答案 0 :(得分:2)

内部查询中不需要联接。
您对外部查询使用相同的别名,而内部查询使用相同的别名,这一事实使我感到困惑,我猜SQL Server也应该对此有问题。 尝试这样写:

DELETE T 
FROM @ProcedureTemp T
WHERE NOT EXISTS
    (
        SELECT *
        FROM Customer C
        -- You already have the T from the outer statement
        WHERE T.CustomerID = C.CustomerID
        AND C.Region = @RegionID
    )