Click here to Skip to main content
15,914,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Sir

I want to insert a new column before or after of a column of the table. What is the query for that ? Please help me sir.



Sashibhusan Meher
Posted

According to my understanding you want to alter table
if it is correct then check here

http://www.w3schools.com/sql/sql_alter.asp[^]

http://sqlserverplanet.com/sql/alter-table-add-column/[^]
 
Share this answer
 
SQL Server does not give you an option to insert a column at a specific point with a query (unlike MySql) - they are always inserted at the end. The only way to do it is:

1) Create a of new table that has got the required structure
2) Copy the data from the original table into this new table
3) Delete the original table
4) Rename the new table to the original table name

Inserting a column at the end is easy:
SQL
ALTER TABLE myTable ADD newColumn INT


To be honest, there is no good reason for inserting a column at a specific column: Unless you specify "all columns" in your SELECT statement (and you shouldn't really do that anyway) you specify the order in which columns are returned, so the order in the DB is irrelevant.
 
Share this answer
 
You can not do it without recreation of the table.

For the proof of this open SSMS and go to design view of a table and insert a row between columns and define its type then click the Generate Change Script button which is located in the left most side of the toolbar by default.
You can see in the script that there is no such insert column command and table was recreated for this purpose.

And another point is that you can reorder columns in select statements and also in insert statements.

Another person that had your problem :
http://stackoverflow.com/questions/2968278/t-sql-add-column-in-specific-order[^]

Hope it helps.
 
Share this answer
 
As already said this cannot be done without recreating the table. The order of the columns in the table is very rarely important.

As OriginalGriff wrote, one situation where this may affect if that if you select everything (*) from the table but even in that case you can refer to the columns of the result set by their names.

The only case I can think of where the this would have any meaning is when the table structure must be highly optimized for data storage and the table may have overflow pages.
 
Share this answer
 

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