2012-10-17 50 views
3

如何從「pippo」表中刪除前18行(按FIELD1排序),然後在另一個名爲minnie的克隆表中插入同一行18行?插入到另一個表中,然後從源表中刪除,然後從源表中刪除

下面的代碼中提取第18行由FIELD1排序,然後將它們刪除:

WITH q AS 
     (
     SELECT TOP 18 * 
     FROM pippo 
     ORDER BY FIELD1 ASC /* You may want to add ORDER BY here */ 
     ) 
DELETE 
FROM q 

我怎樣才能插入相同的18行到米妮表,刪除前?

非常感謝您的幫助。

+1

你爲什麼不只是第一次插入新表中的行並在舊錶中刪除它們? – Tomtom

+0

我怎麼能意識到這一點? – UltraCommit

回答

6

使用

WITH q AS 
     (
     SELECT TOP 18 * 
     FROM pippo 
     ORDER BY FIELD1 ASC /* You may want to add ORDER BY here */ 
     ) 
DELETE 
FROM q 
OUTPUT DELETED.* INTO TableNew 
+0

太好了,謝謝! – UltraCommit

1

如果你願意,你可以嵌套delete一個select內爲insert查詢:

declare @t1 table (Field1 int not null) 
declare @t2 table (Field1 int not null) 

insert into @t1 (Field1) select ROW_NUMBER() OVER (ORDER BY object_id) from sys.objects 

;with First18 as (
    select top 18 * from @t1 order by Field1 
) 
insert into @t2 (Field1) 
select * from 
    (
    delete from First18 output deleted.Field1) t 
相關問題