SQL Server replication table structure to a specified table

Source: Internet
Author: User

Q: May I ask the expert how to copy the structure of other tables to a specified table, such as the following example:

The following three tables are available:

Table A: Field 1, Field 2, Field 3

Table B: Field 1, Field 2, Field 3

Table C: Field 1, Field 2, Field 3

Now you want to copy the fields of table a 1,b The fields of table 2,c table 3 to table 4. The data in the table is not required.

How should you implement SQL statements?

A: In fact, here need to consider a problem, the specified table to the table is not empty? Therefore, we have the following two kinds of situations to say separately:

/*table4不存在时*/
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 will be made. If you want to add these fields to table 4, the data for those fields does not need to be added to table 4

  select
  *
into 表5
from
  表4 m
left join
  (select a.字段1,b.字段2,c.字段3 from 表A a,表B b,表C c where 1<>1) n
on
  1=1
  drop table 表4
  exec sp_rename '表5','表4'

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.