将行从一个表移到另一个表?

时间:2010-05-13 19:11:14

标签: sql-server sql-server-2005 insert-into

我有两个具有相同列定义的表。我需要从一个表移动(不复制)一行到另一个表。在我离开并使用INSERT INTO / DELETE(在事务中)之前,有更聪明的方法吗?

SQL Server 2005

5 个答案:

答案 0 :(得分:32)

对于SQL Server 2005及更高版本,请尝试OUTPUT Clause (Transact-SQL)子句:

DELETE OldTable
  OUTPUT DELETED.col1, DELETED.col2...
      INTO NewTable
  WHERE ID=...

工作示例:

DECLARE @OldTable table(col1 int, col2    varchar(5), col3 char(5), col4     datetime)
DECLARE @NewTable table(col1 int, column2 varchar(5), col3 int    , col_date char(23), extravalue int, othervalue varchar(5))
INSERT @OldTable VALUES (1 , 'AAA' ,'A'  ,'1/1/2010'           )
INSERT @OldTable VALUES (2 , 'BBB' ,'12' ,'2010-02-02 10:11:22')
INSERT @OldTable VALUES (3 , 'CCC' ,null ,null                 )
INSERT @OldTable VALUES (4 , 'B'   ,'bb' ,'2010-03-02'         )

DELETE @OldTable
    OUTPUT DELETED.col1
          ,DELETED.col2
          ,CASE
               WHEN ISNUMERIC(DELETED.col3)=1 THEN DELETED.col3 
               ELSE NULL END
          ,DELETED.col4
          ,CONVERT(varchar(5),DELETED.col1)+'!!'
        INTO @NewTable (col1, column2, col3, col_date, othervalue)
    OUTPUT 'Rows Deleted: ', DELETED.* --this line returns a result set shown in the OUTPUT below
    WHERE col1 IN (2,4)

SELECT * FROM @NewTable

输出:

               col1        col2  col3  col4
-------------- ----------- ----- ----- -----------------------
Rows Deleted:  2           BBB   12    2010-02-02 10:11:22.000
Rows Deleted:  4           B     bb    2010-03-02 00:00:00.000

(2 row(s) affected)

col1        column2 col3        col_date                extravalue  othervalue
----------- ------- ----------- ----------------------- ----------- ----------
2           BBB     12          Feb  2 2010 10:11AM     NULL        2!!
4           B       NULL        Mar  2 2010 12:00AM     NULL        4!!

(2 row(s) affected)

答案 1 :(得分:3)

您可以尝试插入abc(a,b,c) 从def

中选择(a,b,c)

这样做会将def的列a,b,c插入到abc的a,b,c列中。插入后运行删除表,删除表或截断您的标准。

样本是:

Begin
    Begin try

         Begin Transaction

               Insert into emp(name, department, salary)                    
                       Select empName,empDepartment,empSal from employees
                       Where  employees.empID = 211

               Truncate table employees

          End Transaction  

    End try

    Begin Catch

         if @@Error > 0
              Rollback Transaction

    End Catch

End

答案 2 :(得分:0)

SQL中没有MOVE命令。 您必须先从表1插入表2 然后从表1中删除副本。

答案 3 :(得分:0)

不,你几乎坚持在事务中包含插入和删除

答案 4 :(得分:0)

INSERT dbo.newtable(
      name,
      department,
      Salary
) SELECT 
            name,
            FirstName,
            Lastname
      FROM    (
           DELETE dbo.oldtable
           OUTPUT
                   DELETED.name,
                   DELETED.department,
                   DELETED.Salary
           WHERE ID  IN ( 1001, 1003, 1005 )
      ) AS RowsToMove  

SELECT * FROM dbo.newtable
SELECT * FROM dbo.oldtable