[記錄]快速刪除 SQL Server 前 1000 筆資料的方法 Using Common Table Expressions

【注意】CTE 這個方法只適用於MS SQL Server

一般我們刪除指定資料範圍的方式都會用這種方法:

delete from [myTable]
where YourConditions


但是有時候,我們因為某些需要刪除資料庫前1000筆資料時卻好像沒辦法用 where 去達成條件。

我們都知道選擇前 1000 筆資料方式:
select top 1000
field1,field2,field3
from [myTable]


如果把前述條件當成Conditions來用,就必須 join 欄位

delete from [myTable]
where field1 in
(select top 1000
field1
from [myTable])


但很不幸,如果資料龐大,又 field1 不是 Primary Key 的第一欄位,
又或是 Primary Key 是多重組合,則可能造成資料庫大量 LOCK,
使用者得查詢會幾乎被 BLOCK 起來。

這時候我們可以用 CTE 指令方式,這是個類似 Store Procedure 的處理方式,但不需要像 Store Procedure 那樣複雜的語法。

;WITH CTE AS
(
SELECT TOP 1000 *
FROM [myTable]
ORDER BY field1
)
DELETE FROM CTE


看!簡單多了!

關於 CTE 使用方式可以參考 https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms190766(v=sql.105)

※好像SQL2005以上有提供下面指令可以達到效果,但我個人是沒有用過

DELETE TOP (1000)
FROM [myTable]
WHERE YourConditions

留言

這個網誌中的熱門文章

【研究】列印的條碼為什麼很難刷(掃描)

C# 使用 Process.Start 執行外部程式

統一發票列印小程式