Click here to Skip to main content
15,893,668 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I created a table - Programmer
SQL
create TABLE PROGRAMMER(
NAME VARCHAR(16) NOT NULL,
DOB DATE NOT NULL,
DOJ DATE NOT NULL,
SEX VARCHAR(1) NOT NULL,
PROF1 VARCHAR(8) NULL,
PROF2 VARCHAR(8) NULL,
SALARY INT NOT NULL
)

now i want to insert the ID column(ID int not null) before NAME column.how it will be possible.Any idea please let me know.I want to write the query for the same.

Thanking in advance

What I have tried:

i google for the same but there is no idea for inserting the column before existing column.I google its shows inserting the column after existing the column which i dont need.
Posted
Updated 1-Apr-16 19:08pm
Comments
CHill60 1-Apr-16 9:37am    
Not entirely sure why you would want to do that, the order of columns in the table is meaningless. AFAIK you would have to drop the table and recreate it.
R Harshal 1-Apr-16 9:58am    
apart from droping the table ,so you mean to say there is no way to add column before exsisting column.
CHill60 1-Apr-16 10:26am    
See Solution 1 - it mentions the only two ways I know of doing it. Neither are particularly nice. See also the comment from RickZeeland - if you have existing import applications that use this table moving the columns around could break them
RickZeeland 1-Apr-16 10:16am    
In exceptional cases you can get issues when the column order is not the same. I had a problem with importing CSV data with the BCP (Bulk Copy) utility once.
Karthik_Mahalingam 1-Apr-16 9:45am    
you cant do that.

This is not possible directly, I'm afraid. TransacSQL does not have any instruction regarding the order of columns in tables.

You can do that graphically with SQL Server Management Studio.

If you really want to do it programmatically, you have to create a temporary table which mimics the schema of the original table, adding the new column at the right place in the process, then delete the original, and finally rename the temp table to the name of the original one.
 
Share this answer
 
Comments
CHill60 2-Apr-16 7:46am    
No idea why this solution was given a 1-vote so I've countered it with a 5.
phil.o 2-Apr-16 7:49am    
Thanks :)

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