Search This Blog

Monday, June 11, 2012

Delete from table using join SQL Server

SQL Server > DML > DELETE

Removes rows from a table.

Example

To delete from tables using join you must specify an alias for the table from which to delete data.

IF OBJECT_ID(N'tbl1', N'U') IS NOT NULL
       DROP TABLE tbl1;
GO
IF OBJECT_ID(N'tbl2', N'U') IS NOT NULL
       DROP TABLE tbl2;
GO

CREATE TABLE tbl1
(
       id           int ,
       name   varchar(50)
);
GO
CREATE TABLE tbl2
(
       id           int ,
       name   varchar(50)
);
GO

INSERT INTO tbl1 values  (1,'john'), (2,'dan') , (3,'laura')
INSERT INTO tbl2 values  (1,'john')
GO

select * from tbl1
--id name
--1 john
--2 dan
--3 laura
DELETE
  a
from
  tbl1 a
join tbl2 b on a.id = b.id

select * from tbl1

--id name
--2 dan
--3 laura



GO