2014-04-24 88 views
1

我想刪除除頂部x值之外的所有值,但我不太確定我做錯了什麼。SQL刪除除頂部x之外的全部x

我的查詢:

DELETE FROM dbo.cake 
where dbo.cake.pie not in (select top 500 * from dbo.cake 
where createdDate >= '2007-01-01' 
and createdDate < '2008-01-01') 

我得到的錯誤是:

Msg 116, Level 16, State 1, Line 4 
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS. 

任何和所有幫助表示讚賞!

回答

4

更改爲

DELETE FROM dbo.cake 
where dbo.cake.pie not in (select top 500 pie from dbo.cake 
where createdDate >= '2007-01-01' 
and createdDate < '2008-01-01') 
+0

謝謝,我會在讓我接受這個答案。聖潔..這個查詢已經花了5分鐘到目前爲止運行,它仍然是! – Zain

+0

您可能想要在createdDate列上添加索引。我假設派有主鍵已經。 –

+0

誠實地說,我甚至不知道該怎麼做。在嘗試執行查詢後出現此錯誤:(.. Msg 547,Level 16,State 0,Line 1 DELETE語句與REFERENCE約束「FK_donuts_tastenice」衝突。數據庫「food_qa」中發生衝突,表「dbo該聲明已終止 – Zain

4

嘗試把外地的子查詢

DELETE FROM dbo.cake 
where dbo.cake.pie not in (select top 500 pie from dbo.cake 
where createdDate >= '2007-01-01' 
and createdDate < '2008-01-01') 
+0

謝謝您的幫助:)。 – Zain

1

試試這個:

WITH CTE AS (SELECT *,RN=ROW_NUMBER() OVER (ORDER BY foo) FROM dbo.cake) 
DELETE FROM CTE 
WHERE RN>500 
AND createdDate >= '2007-01-01' 
and createdDate < '2008-01-01'