mikaelsnavy
11/20/2014 - 7:54 PM

Delete multiple rows on row at a time

Delete multiple rows on row at a time

IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL DROP TABLE #TEMP

--This will work since each delete is done as a single row
SELECT RowNum = ROW_NUMBER() OVER(ORDER BY ct_id), ct_id 
INTO #TEMP
FROM ct_note where ntype_id IN('{d94f685c-84ec-49b2-8e0f-ebaf9f6e609f}', '{afbf6d79-6d77-41e6-8790-9505e9b9ed82}', '{6cad622d-c3b7-4907-b62a-a882902ee4e4}')


DECLARE @MaxRownum INT
SET @MaxRownum = (SELECT MAX(RowNum) FROM #TEMP)

DECLARE @Iter INT
SET @Iter = (SELECT MIN(RowNum) FROM #TEMP)

WHILE @Iter <= @MaxRownum
BEGIN
    SELECT *
    FROM #TEMP
    WHERE RowNum = @Iter
    
    DELETE FROM ct_note where ct_id = (SELECT ct_id from #TEMP where RowNum = @Iter)
    
    SET @Iter = @Iter + 1
END

DROP TABLE #TEMP