Ms SQL Server table replication

Source: Internet
Author: User

I. Could you tell me how to copy the structure of other tables to a specified table? For example:

There are three tables:

Table A: Field 1, Field 2, and field 3

Table B: Field 1, Field 2, Field 3

Table C: Field 1, Field 2, Field 3

Now, we want to copy fields 1 in Table A, 2 in Table B, and 3 to 4 in table C. No data in the table is required.

How should I use SQL statements?

A: Actually, we need to consider the following question: is the specified table empty? Therefore, we can talk about the following two situations:

/* When Table 4 does not exist */

Select a. col1, B. col2, C. col3
Into table4
From tablea A, tableb B, tablec C
Where 1 = 0

However, if Table 4 already exists, an error is returned. If you want to add these fields to table 4, but the data of these fields does not need to be added to table 4

Select
*
Into Table 5
From
Table 4 m
Left join
(Select a. Field 1, B. Field 2, C. Field 3 from Table A, table B, table C where 1 <> 1) N
On
1 = 1

Drop table 4

Exec sp_rename 'table 5', 'table 4'

2. 1. duplicate the same two tables

Insert into target database name. DBO. Table Name select * from source database name. DBO. Table Name

2. Description: copy a table (only copy structure, source table name: a new table name: B)

SQL: Select * into B from a where 1 <> 1

3. Description: copy a table (copy data, source table name: A target table name: B)

SQL: insert into B (a, B, c) Select D, E, F from B;
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.