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; |