Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Delete statement

Author  Topic 

Delinda
Constraint Violating Yak Guru

315 Posts

Posted - 2010-04-06 : 23:32:08
My tables and rows as follow,
declare @Departments table
(DepartmentID int identity(1,1),Name varchar(30));
insert into @Departments values('D1');
insert into @Departments values('D2');
insert into @Departments values('D3');
insert into @Departments values('D4');

declare @Employees table
(EmployeeID int identity(1,1),[First Name] varchar(20),[Last Name] varchar(20),DepartmentID int);
insert into @Employees values('John','Smith',1);
insert into @Employees values('Dave','Johnson',2);
insert into @Employees values('Mark','Andrew',2);
insert into @Employees values('George','Michael',4);
insert into @Employees values('Michael','Peterson',3);


My result as follow,

select EmployeeID,t2.DepartmentID,[First Name] + ' ' + [Last Name] as 'EmployeeFullName'
,t2.Name as DepartmentName
from @Employees t1 inner join @Departments t2
on t1.DepartmentID=t2.DepartmentID

Output
---------------------------------------------------------------------
EmployeeID | DepartmentID | EmployeeFullName | DepartmentName
1 1 John Smith D1
2 2 Dave Johnson D2
3 2 Mark Andrew D2
4 4 George Michael D4
5 3 Michael Peterson D3


My question is
1. How to delete employees with DepartmentName='D2' using subquery?
2. How to delete employees with DepartmentName='D2' using without using subquery?

pk_bohra
Master Smack Fu Yak Hacker

1182 Posts

Posted - 2010-04-07 : 00:02:47
Using subquery:

Delete from @Employees where DepartmentId in (Select departmentId from @Departments where name='D2')

Without using subquery -- You need to use a variable for this.

Declare @DeptId int
Select @Deptid = DepartmentId from @Departments where name ='D2'

Delete from @Employees where DepartmentId = @Deptid


Regards,
Bohra


Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-04-07 : 00:18:05
for second one you can dispense with variable and directly use

Delete e
from @Employees e
join @Departments d
on d.DepartmentID = e.DepartmentID
where d.Name ='D2'


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

Delinda
Constraint Violating Yak Guru

315 Posts

Posted - 2010-04-07 : 00:24:35
tq sir
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-04-07 : 00:26:51
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -