且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SQL中的现有列之前插入列

更新时间:2023-12-01 11:01:40

这是不可能直接的,我害怕。 TransacSQL没有关于表中列顺序的任何指令。



您可以使用SQL Server Management Studio以图形方式执行此操作。



如果你真的想以编程方式进行,你必须创建一个临时表来模仿原始表的模式,在过程中的正确位置添加新列,然后删除原始表,最后将临时表重命名为原始表的名称。


简单答案是,但是可以使用一些不推荐的脚本来完成



alter table - 在另外两列之间添加列SQL服务器 [ ^ ]

SQL SERVER - 如何添加列表中的具体位置 [ ^ ]

插入SQL Server中其他列之间的列使用脚本 - Stack Overflow [ ^

I created a table - Programmer

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.

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.


Simple answer is NO , but can be done with some scripts which is not recommendable

alter table - Adding column between two other columns in SQL server [^]
SQL SERVER - How to Add Column at Specific Location in Table [^]
Inserting column between other columns in SQL Server using script - Stack Overflow[^]