zoukankan      html  css  js  c++  java
  • Insert Data From One Table to Another Table

    Following three questions are many time asked on this blog.

    How to insert data from one table to another table efficiently?
    How to insert data from one table using where condition to anther table?
    How can I stop using cursor to move data from one table to another table?

    There are two different ways to implement inserting data from one table to another table. I strongly suggest to use either of the method over cursor. Performance of following two methods is far superior over cursor. I prefer to use Method 1 always as I works in all the case.

    Method 1 : INSERT INTO SELECT
    This method is used when table is already created in the database earlier and data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are are not required to list them. I always list them for readability and scalability purpose.
    USE AdventureWorks
    GO
    ----Create TestTable
    CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
    ----INSERT INTO TestTable using SELECT
    INSERT INTO TestTable (FirstName, LastName)
    SELECT FirstName, LastName
    FROM Person.Contact
    WHERE EmailPromotion = 2
    ----Verify that Data in TestTable
    SELECT FirstName, LastName
    FROM TestTable
    ----Clean Up Database
    DROP TABLE TestTable
    GO

    Method 2 : SELECT INTO
    This method is used when table is not created earlier and needs to be created when data from one table is to be inserted into newly created table from another table. New table is created with same data types as selected columns.
    USE AdventureWorks
    GO
    ----Create new table and insert into table using SELECT INSERT
    SELECT FirstName, LastName
    INTO TestTable
    FROM Person.Contact
    WHERE EmailPromotion = 2
    ----Verify that Data in TestTable
    SELECT FirstName, LastName
    FROM TestTable
    ----Clean Up Database
    DROP TABLE TestTable
    GO

    Both of the above method works with database temporary tables (global, local). If you want to insert multiple rows using only one insert statement refer article

  • 相关阅读:
    MongoDB的下载与安装
    Oracle PL/SQL 编程手册(SQL大全)
    内部类、异常、其他
    异常(补充)
    final、抽象类、接口、多态、
    改变JVM中的参数以提高Eclipse的运行速度
    Java中的三目运算符 详解
    Java中的Stringbuffer类解析
    Staitic(静态) 相关知识点介绍
    Java反射
  • 原文地址:https://www.cnblogs.com/Excellentchen/p/1922906.html
Copyright © 2011-2022 走看看