Wednesday, July 11, 2007

Based a table A, to delete record(s) from a table B

USE Adata
GO
CREATE TABLE Customers
(CustomerID INT PRIMARY KEY,
Fullname VARCHAR(50) NOT NULL,
AccessDate Datetime DEFAULT Getdate()
)
GO
CREATE TABLE Products
(
ProductID INT PRIMARY KEY,
CustomerID INT FOREIGN KEY REFERENCES Customers(CustomerID),
ProductName VARCHAR(50) NOT NULL
)
GO
INSERT INTO Customers VALUES(1,'John Smith','May 1, 2002');
INSERT INTO Customers VALUES(2,'Kevin Smith','May 4, 2002');
INSERT INTO Customers VALUES(3,'Devin Clarke','May 5, 2002');
INSERT INTO Customers VALUES(4,'Inkaran Tharmas','May 7, 2002');
GO
INSERT INTO Products VALUES(1,1,'Coffee Bean');
INSERT INTO Products VALUES(2,1,'Shriek Movie');
INSERT INTO Products VALUES(3,1,'DDR RAM');
INSERT INTO Products VALUES(4,2,'Coffee Bean');
INSERT INTO Products VALUES(5,2,'Tool Kit');
INSERT INTO Products VALUES(6,2,'Hose');
INSERT INTO Products VALUES(7,2,'Soy Bean');
GO
SELECT * FROM Customers

CustomerID Fullname AccessDate
----------- ------------------------- -----------------------
1 John Smith 2002-05-01 00:00:00.000
2 Kevin Smith 2002-05-04 00:00:00.000
3 Devin Clarke 2002-05-05 00:00:00.000
4 Inkaran Tharmas 2002-05-07 00:00:00.000

(4 row(s) affected)

In the Products table, only two customers order products.
You want to delete the records that don't have the order history in Products table.

DELETE FROM Customers
FROM Customers C LEFT JOIN Products P
ON C.CustomerID=P.CustomerID
WHERE P.CustomerID IS NULL;
GO

SELECT * FROM Customers

CustomerID Fullname AccessDate
----------- -------------------------- -----------------------
1 John Smith 2002-05-01 00:00:00.000
2 Kevin Smith 2002-05-04 00:00:00.000

(2 row(s) affected)