views:

659

answers:

4

I know in SQL Server 2005 we could do something like:

DELETE TOP 10 FROM tbX where X = 1

What could be the query to do the same in SQL2K, considering that the primary key is composed by two FK columns?

+1  A: 
DELETE
FROM tbX
WHERE id IN (SELECT TOP 10 id FROM tbX WHERE X = 1)

You would have to delete the foreign key records first.

Chris Klepeis
I don't have an 'id'. Primary key is composed by two FK columns.
Victor Rodrigues
A: 

when dealing with a composite key I would delete like this.

delete from tblX
from tblx as aa
join
(
  select top 10 * from tblX
) as bb
on
  aa.key1 = bb.key1
  and
  aa.key2 = bb.key2
automatic
+2  A: 

hacky, but:

SET ROWCOUNT 10
DELETE FROM tbX where X = 1
SET ROWCOUNT 0

I wouldn't write this myself, though ;-p

(I'm off to wash my hands...)

Marc Gravell
i've used this hack a coupla times myself. and now, i'm off to wash my hands...
Raj More
my previous job had this reporting framework and they had the brilliant idea to restrict all reports to 50,000 rows using set rowcount, needless to say, reports that returned only 100 rows could end up having the wrong results if they needed to churn through to much data.
Sam Saffron
Yes - very dangerous if you don't limit it to very tightly scoped and understood operations. Actually, I could just stop at "very dangerous".
Marc Gravell
I did this, very hacky, but useful in my case, since I have SQL2K ;)
Victor Rodrigues
A: 

This is not working SQL but something along the lines may work:

DELETE t
from tbx t 
join (
  select top 10 k1,k2 from tbx
) as t2 on t.k1 = t2.k1 and t.k2 = t2.k2

Note: If TOP does not work in the subquery just insert the stuff into a temp table and join.

Sam Saffron

related questions