Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new table column to specific ordinal position in Microsoft SQL Server

Is it possible to add a column to a table at a specific ordinal position in Microsoft SQL Server?

For instance, our tables always have CreatedOn, CreatedBy, LastModifiedOn, LastModifiedBy columns at the "end" of each table definition? I'd like the new column to show up in SSMS above these columns.

If I am scripting all my database changes, is there a way to preserve this order at the end of the table?

FYI, I'm not trying to institute a flame war on if this should even be done. If you want to read about a thread that degenerates quickly into that, here's a good one:

http://www.developersdex.com/sql/message.asp?p=581&r=5014513

like image 789
Even Mien Avatar asked Apr 20 '09 19:04

Even Mien


People also ask

Can we add a column in a specific position in SQL Server?

To add a column at a specific position within a table row, use FIRST or AFTER col_name . The default is to add the column last. You can also use FIRST and AFTER in CHANGE or MODIFY operations to reorder columns within a table.

How do I change the ordinal position of a column in SQL Server?

In Object Explorer, right-click the table with columns you want to reorder and select Design. Select the box to the left of the column name that you want to reorder. Drag the column to another location within the table.


2 Answers

You have to create a temp table that mirrors the original table's schema but with the column order that you want, then copy the contents of the original to temp. Delete the original and rename the temp.

This is what SQL Management Studio does behind the scenes.

With a schema sync tool, you can generate these scripts automatically.

like image 174
Jose Basilio Avatar answered Sep 21 '22 15:09

Jose Basilio


go into SQL Server management Studio, and "design" an existing table. Insert a column in the middle, right click in an empty area and select Generate Change Script...

Now look at the script it creates. it will basically create a temp table with the proper column order, insert the data from the original table, drop the original table, and rename the temp table. This is probably what you'll need to do.

enter image description here

You may also need to uncheck this option to allow creation of change scripts

enter image description here

like image 20
KM. Avatar answered Sep 18 '22 15:09

KM.