Click here to Skip to main content
15,912,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to add the column in between two columns in SQL server

This is my sql query but is not working it display some errors

SQL
alter table [login] add mobileno bigint not null AFTER UserName
Posted
Updated 6-Mar-18 17:49pm
Comments
ssd_coolguy 7-Jun-12 2:56am    
hey i don't think is there any way to add column in between two existing column using TSQL.for that you need to use temp table or Enterprise Manager will write all of the code for you...:)

You can't insert columns, without creating a new table including the column in the position you want, and copying the info over, before deleting the old table and renaming the new.

The only reason for wanting columns in a specific order is because you are using SELECT * FROM syntax: which is a bad practice anyway for a number of reasons. Firstly, because it causes your program to behave differently or fail if the database is changed externally, and secondly because it is a serious waste of bandwidth to return columns you are not interested in. Always explicitly list the columns you want to retrieve, or affect as this can mean that a problem is picked up before it goes on to damage significant amounts of data in your database.
 
Share this answer
 
Comments
VJ Reddy 7-Jun-12 3:20am    
Good answer. 5!
Maciej Los 7-Jun-12 3:24am    
Good answer, my 5!
AFAIK, you cannot insert a new column between two existing one using a query or a script. Using GUI, you can by selecting the column row in table-design and choosing insert a column option.

The main thing is why does that matter at all? There is no difference in which order a particular column lies in SQL table. You can always have desired result in your queries and views designed based on the tables.
 
Share this answer
 
Comments
VJ Reddy 7-Jun-12 3:20am    
Good answer. 5!
Maciej Los 7-Jun-12 3:23am    
Good answer, my 5!
You can not do this programatically (in a safe way that is) without creating a new table. There isn't another way to insert a column in a SQL Server table "in between" existing columns - you need to build a temp table and rebuild the old table.

What Enterprise Manager does when you commit a reordering is to create a new table, move the data and then delete the old table and rename the new table to the existing name.

If you want your columns in a particular order/grouping without altering their physical order, you can create a view which can be whatever you desire.
 
Share this answer
 
Comments
VJ Reddy 7-Jun-12 3:20am    
Good answer. 5!
codeBegin 8-Jun-12 2:12am    
:) thank you
Maciej Los 7-Jun-12 3:24am    
Good answer, my 5!
codeBegin 8-Jun-12 2:12am    
thank you :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900