Adding column between two other columns in SQL server

谁说胖子不能爱 提交于 2019-12-17 20:21:50

问题


Can you add a column to a table inserting it in between two existing columns in SQL Server without dropping and re-creating the table?


回答1:


The simple answer is no. Is there a reason why column order is important to you?




回答2:


Mediumly long answer, yes (ish) but it's ugly and you probably wouldn't want to do it.

please note: this code creates a physical table

CREATE TABLE MyTest (a int, b int, d int, e int)

INSERT INTO MyTest (a,b,d,e) VALUES(1,2,4,5)

SELECT * FROM MyTest

ALTER TABLE MyTest ADD c int
ALTER TABLE MyTest ADD d_new int
ALTER TABLE MyTest ADD e_new int

UPDATE MyTest SET d_new = d, e_new = e

ALTER TABLE MyTest DROP COLUMN d
ALTER TABLE MyTest DROP COLUMN e

EXEC SP_RENAME 'MyTest.d_new', 'd';
EXEC SP_RENAME 'MyTest.e_new', 'e';

SELECT * FROM MyTest 

DROP TABLE MyTest



回答3:


Take a look at this link:

http://www.bobsgear.com/display/ts/Adding+Column+After+Another+Column+-+SQL+Server+2005

As you can see, the answer is:

'not possible without moving data to a temp table'

which is what the SQL Server Management Studio actually does.




回答4:


Yes you can add here is the query for your concern:

ALTER table table_name ADD column column_name(new) datatype AFTER column_name



回答5:


First answer, no.

Second answer, according to this thread http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=58912, found via Can I logically reorder columns in a table?, you could create the column then reorder the columns in the table by editing the system tables. But it looks incredibly messy and I would not trust that things would not break.




回答6:


yes. You can drag and drop it in design mode, or copy and paste it in edit table mode


in response to comments, yes, this is with SQL Server Management Studio through the UI, and under the hood, it's doing the drop/recreate you're trying to avoid, so no, you can't do it without the server doing it for you.



来源:https://stackoverflow.com/questions/5327545/adding-column-between-two-other-columns-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!