I used SSMS to add a composite primary key to a table with 64 million rows.
Because the table was so large, I used the change script generated by SSMS. One of the PK fields (REVENUE_CODE) originally allowed NULLs, so the change script changed it to NOT NULL in the CREATE TABLE statement.
Here's a simplified version of the change script from SSMS:
BEGIN TRANSACTION GO -- PART 1 Succeeded CREATE TABLE dbo.Tmp_Charges ( RECORD_ID VARCHAR(12) NOT NULL, REVENUE_CODE VARCHAR(4) NOT NULL, UNITS_OF_SERVICE VARCHAR(7) NULL, ) GO -- PART 2 Succeeded ALTER TABLE dbo.Tmp_Charges SET (LOCK_ESCALATION = TABLE) GO -- PART 3 Failed because there were NULL values in the REVENUE_CODE field IF EXISTS(SELECT * FROM dbo.Charges) EXEC('INSERT INTO dbo.Tmp_Charges (RECORD_ID, REVENUE_CODE, UNITS_OF_SERVICE) SELECT RECORD_ID, REVENUE_CODE, UNITS_OF_SERVICE FROM dbo.Charges WITH (HOLDLOCK TABLOCKX)') GO -- PART 4 Succeeded DROP TABLE dbo.Charges GO -- PART 5 Succeeded EXECUTE sp_rename N'dbo.Tmp_Charges', N'Charges', 'OBJECT' GO -- PART 6 Succeeded ALTER TABLE dbo.Charges ADD CONSTRAINT PK_Charges PRIMARY KEY CLUSTERED ( RECORD_ID, REVENUE_CODE ) GO COMMIT When I ran the script, Parts 1 and 2 succeeded, but Part 3 failed because there were NULL values in the REVENUE_CODE field that I didn't know about or check for.
I assumed the entire transaction would fail and changes would be rolled back, but it didn't. All the other parts succeeded, and I was left with an empty table.
What did I misunderstand about this script? Why weren't the changes rolled back?
GOdoesn't work for you) you can enable SQL CMD mode in SSMS and add:on error exitto the top of the script to avoid it continuing on and executing subsequent batches. .Still useXACT_ABORTthough