views:

207

answers:

4

How to rearrange column order in sql server ?

right now my column is showing like below when i physically right click and take properties: in sql server 2005

colA1
colA2
colA3
colA4
colB1
colB2
colB3
colA5
colA6

Since i know these columns (colA5,colA6) are created new !

How to make it like this ?

colA1
colA2
colA3
colA4
colA5
colA6
colB1
colB2
colB3
+2  A: 

You can do this easily enough in the designer (SSMS) - just drag the columns around to the correct order and then save - in the background it will script out and re-create the table.

But why do you need to do it? Order of columns has no impact other than making things look pretty in the designer.

Chris W
Gary McGill
Enforcing this on any kind of decent sized database is this issue - if someone starts re-ordering columns in a live DB using the designer doesn't appreciate what happens under the covers of SSMS then they get a big surprise when the table locks up as it's recreated.
Chris W
Note Mar Gravell's comment on this issue where the table is replicated as another reason...
Chris W
@Chris W: Good point well made! Re-ordering columns in SSMS drops and and recreates the table behind the scenes. If you're at the design stage of your database no problem but if it's a live table with millions of records you could be in for trouble.
John Sansom
The best idea is don't do this - the order of columns should not be relied upon or changed; basic rule of defensive programming with SQL.
onupdatecascade
+2  A: 

Can you just use a view based on the table to get the output you want? That's my first reaction.

Galwegian
+2  A: 

Right-click on the table, choose "Design", then drag the columns up or down.

Gary McGill
+4  A: 

Moving columns involves a lot of DDL, and doesn't actually do anything.

If the table is currently empty, fine... but if it has lots of data, this can be very painful. And if the table is currently replicated: even worse.

IMO, you should just handle this in the SELECT statement:

SELECT colA1, colA2, colA3, colA4, colA5, colA6, colB1, colB2, colB3
FROM   TheTable
Marc Gravell