I’m using sql server 2005
the idea is to create a column, update the values to 0, make it not nullable then, and recreate an existing PK adding it to the list
so far i’ve got this :
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MyTable' AND COLUMN_NAME = 'Division')
BEGIN
ALTER TABLE MyTable ADD Division int NULL
UPDATE MyTable SET Division = 0
ALTER TABLE MyTable ALTER COLUMN Division int NOT NULL
ALTER TABLE [dbo].[MyTable] DROP CONSTRAINT [PK_MyTable]
ALTER TABLE [dbo].[MyTable] ADD CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED
(
[ID] ASC,
[OfferCode] ASC,
[StationCode] ASC,
[Market] ASC,
[Division] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END
The problem is that i need a “GO” statement so that the new column is created, otherwise i get an error when trying to update the values to 0. If i put a “GO” statement, then the if clause doesn’t work (because the column now exists). i was thinking of putting that status to a variable like @ColumnWasCreated, but the “GO” statement is like starting a whole new script, and the variable’s value is lost
any ideas??
OPTION 1
Instead of
GO, try aTRANSACTIONthat encompasses theADD COLUMN; then commit it and see if you canUPDATE.OPTION 2
Try setting a default value constraint when you
ADD COLUMN, this way, you won’t have toUPDATEorALTERto not allownulls.