我正在尝试使用脚本更改 SQL Server 中的表。过去我总是通过 GUI 来完成这种事情,但现在我需要生成一个脚本来为客户做这件事。
我有一个如下所示的 SQL Server 数据库表:
MyTable ------- ColA int NOT NULL ColB int NOT NULL ColC int NOT NULL ColD VARCHAR(100)
The primary key is defined across ColA, ColB, and ColC.
I want the SQL script to change the table like so:
MyTable ------- ColA int NOT NULL ColB int NOT NULL ColX int NOT NULL (new column, default 0 for existing data) ColC int NOT NULL ColD VARCHAR(100)
The primary key would now be defined by ColA, ColB, ColX, and ColC.
This is easy to do through SQL Server GUI. But when I have it generate a script from that, it seems unnecessarily complex. Basically, the script creates a temporary table with the new schema, copies all the data, indexes, and constraints from the old table into the temp table, deletes the old table, then renames the new one to the name of the old one. In addition, it has lines like this:
ALTER TABLE dbo.Tmp_MyTable ADD CONSTRAINT
MyTable21792984_ColC_DF DEFAULT ((0)) FOR ColC
我担心这些看起来随机的数字(即 21792984)在所有客户数据库实例上都不相同。它们看起来像是 SQL 服务器在创建数据库时生成的东西,对于每个实例来说都是唯一的。
是否有更直接的方法通过 SQL 命令更改表?我在网上查过,但发现的内容大多是基本的和/或通用的。
更新:从我收到的答案来看,困难在于将新列“放在”两列“之间”。我意识到列的顺序并不重要(如果我错了,请随时留下答案来纠正我)。就我而言,如果我只是将列添加到表的末尾,并且代码中没有任何内容依赖于特定的列顺序,则更改会简单得多。
最佳答案
没有其他方法可以在 SQL Server 表中的现有列“之间”插入列 - 您需要构建临时表并重建旧表。也就是说,列顺序并不重要 - 您确定需要按顺序插入列吗?
您最好的选择可能是只使用 GUI,将其编写为脚本,然后将约束名称更改为脚本中合理的名称。您说得对,数字约束名称并不理想,并且允许 SQL Server 确定您的对象名称也不是最佳实践。
关于sql - 使用脚本在 SQL Server 中的其他列之间插入列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/965927/