I'm trying to add a column to the end of a table in SQL like so:
For some reason, when my colleagues do this, it generates the usual ALTER TABLE
script.
When I attempt this, it generates a script that Creates a temporary table, then drops the existing table, then replaces the original table with the temp table, like so:
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.Table_Name
DROP CONSTRAINT DF_Table_Name_NewColumnName
GO
CREATE TABLE dbo.Tmp_Table_Name
(
Id int NOT NULL IDENTITY (1, 1),
Column1 varchar(16) NOT NULL,
NewColumnName int NOT NULL,
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_Table_Name SET (LOCK_ESCALATION = TABLE)
GO
ALTER TABLE dbo.Tmp_Table_Name ADD CONSTRAINT
DF_Table_Name_NewColumnName DEFAULT ((1)) FOR NewColumnName
GO
SET IDENTITY_INSERT dbo.Tmp_Table_Name ON
GO
IF EXISTS(SELECT * FROM dbo.Table_Name)
EXEC('INSERT INTO dbo.Tmp_Table_Name (Id, Column1, NewColumnName)
SELECT Id, Column1, NewColumnName FROM dbo.Table_Name WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_Table_Name OFF
GO
DROP TABLE dbo.Table_Name
GO
EXECUTE sp_rename N'dbo.Tmp_Table_Name', N'Table_Name', 'OBJECT'
GO
ALTER TABLE dbo.Table_Name ADD CONSTRAINT
PK_Table_Name PRIMARY KEY CLUSTERED
(
Id
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
COMMIT
I can understand why it may do this if I'm dropping columns, or adding columns in the middle of the table, but I'm not, I'm simply adding a column to the end of the table.
This problem has actually caused SQL Server to delete all data in the table, if there is anything wrong with the design (I originally caught this by forgetting to add a default value to a required column, it wiped all data in the table.. Thankfully only in a development environment).
Adding this answer for reference.
If you add a column as the last column and make the column Not NULL, then you will get prompted to drop and recreate the table. To get around this, add a Default value so it knows what what value to set existing rows to.