Tuesday, June 7, 2011

SQL Server: Using JOIN Clause(s) with UPDATE and DELETE

SQL Server JOINs are very useful in data processing.
They are commonly used in SELECT queries but can be used with UPDATE and DELETE statements.

E.g.

IF OBJECT_ID('TableA') IS NOT NULL THEN
BEGIN
           DROP TABLE TableA
END
GO

IF OBJECT_ID('TableB') IS NOT NULL THEN
BEGIN
           DROP TABLE TableB
END
GO

CREATE TABLE TableA(
ID INT,
Name VARCHAR(100)
)
GO

CREATE TABLE TableB(
ID INT,
Name VARCHAR(100)
)
GO

Lets assume that these tables are populated with some records.

UPDATE ta
SET ta.Name = 'Join clause with Update statement'
FROM TableA ta
INNER JOIN TableB tb ON ta.ID = tb.ID
GO

DELETE ta
FROM TableA ta
INNER JOIN TableB tb ON ta.ID = tb.ID
GO

Similar to INNER JOIN, other types of JOIN clauses like LEFT JOIN and RIGHT JOIN can also be used with UPDATE and DELETE statements.

Please review this article and provide your comments.

Reference: DP (http://dptechnicalblog.blogspot.com/ )

No comments:

Post a Comment