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'