INSERT到另一个表,然后从源表中删除

时间:2012-10-17 10:20:44

标签: sql sql-server-2005

如何从“pippo”表中删除前18行(按FIELD1排序),然后在另一个名为minnie的克隆表中插入相同的18行?

以下代码提取FIELD1排序的前18行,然后删除它们:

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

如何在删除之前将相同的18行插入minnie表中?

提前感谢您的帮助。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

如果您愿意,可以将delete嵌套在selectinsert查询:

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