简体   繁体   中英

Copying a SQL Server table and adding and rearranging columns

I know that if I want to make a copy of a SQL Server table, I can write a query akin to this:

SELECT * 
INTO NewTable
FROM OldTable

But what if I wanted to take the contents of OldTable that may look like this:

| Column1 | Column2 | Column3 |
|---------|---------|---------|
| 1       | 2       | 3       |
| 4       | 5       | 6       |
| 7       | 8       | 9       |

and make a copy of that table but have the new table look like this:

| Column1   | Column3   | Column2   | Column4   | Column5   |
|---------  |---------  |---------  |---------  |---------  |
| 1         | 3         | 2         | 10        | 11        |
| 4         | 6         | 5         | 12        | 13        |
| 7         | 9         | 8         | 14        | 15        |

So now I've swapped Columns 2 and 3 and added Column 4 and Column 5. I don't need to have a query that will add that data to the columns, just the bare columns.

It's a matter of modifying your select statement. SELECT * takes only the columns from the source table, in their order. You want something different - so SELECT it.

SELECT * INTO NewTable
  FROM OldTable

->

SELECT Col1, col3, col2, ' ' AS col4, ' ' AS col5
  INTO NewTable
  FROM OldTable

This gives you very little flexibility as far as how the table's columns are specced and indices and such - so it's probably a bad idea, probably better to do this another way (properly CREATE TABLE ), but if you need quick and dirty, I suppose...

You can just name the columns:

Select
[Column1], [Column3], [Column2], Cast(null as bigint) as [Column4], 0 as [Column5]
Into CopyTable
From YourTable

Just like any query, it is always preferable to use the Column names and avoid using * .

You can then add any value as [ColumnX] in the select. You can use a cast to get the type you want in the new table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM