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 2000 Forums
 SQL Server Development (2000)
 Deleting from one table in a join?

Author  Topic 

aiken
Aged Yak Warrior

525 Posts

Posted - 2002-12-10 : 13:16:51
I've got a scenario like this:
CREATE TABLE users (i int identity, login varchar(20), last_login smalldatetime)
CREATE TABLE user_records (i_users int, d1 int, d2 in2)
Now, if I want to delete all of the user_records for users who haven't logged in in the past 30 days, what's the best way to do this? Selecting the records is easy:
select * from user_records join users on i_users=users.i where last_login<=dateadd(day,-30,getdate())
...But that's not going to work for a delete. So far, I've come up with:
delete from user_records where i_users in (select i from users where last_login<=dateadd(day,-30,getdate())
...But that seems kind of ugly. The other alternative I see is:
delete from user_records where (select last_login from users where users.i=user_records.i_users)<dateadd(day,-30,getdate())
...But that seems even worse (one select per user_record). Anyone have any thoughts on this? I feel like I'm missing something fundamental. What I want is something like:
delete from user_records join users on user_records.i_users=users.i where last_login<=dateadd(day,-30,getdate())
...But that doesn't seem to exist, syntactically.

Thanks
-b

AndrewMurphy
Master Smack Fu Yak Hacker

2916 Posts

Posted - 2002-12-10 : 13:38:21
nearly there in the syntax....

see below for some help....got via a FORUM SEARCH using "DELETE JOIN ON".....

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=22168


HTH


Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2002-12-10 : 13:54:18
Try this:

delete from user_records
from user_records ur
join users u on ur.i_users = u.i
where last_login <= dateadd(day, -30, getdate())

Go to Top of Page

aiken
Aged Yak Warrior

525 Posts

Posted - 2002-12-10 : 21:15:25
Thanks for the help -- for what it's worth, the delete join worked, but performance was terrible. The same data was deleted *much* more quickly using the IN and subquery...

Cheers
-b

Go to Top of Page
   

- Advertisement -