Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Alex-Yates/dc3d30c5fa6431a2761840422445c747 to your computer and use it in GitHub Desktop.
Save Alex-Yates/dc3d30c5fa6431a2761840422445c747 to your computer and use it in GitHub Desktop.
/*
Run this script on the standard SimpleTalk demo database to create a new NOT NULL column but grab the data from a different column
(SSDT can't do this in an automated way)
*/
PRINT N'Adding [Person].[Address].[CreatedDate] column (empty)'
GO
ALTER TABLE [dbo].[Contacts]
ADD [CreatedDate] [datetime] NULL
GO
PRINT N'Populating existing rows with data from the [ModifiedDate] column'
GO
UPDATE [dbo].[Contacts] -- <== State-based approach can't handle this
SET [CreatedDate] = [ModifiedDate]
WHERE [CreatedDate] IS NULL
GO
PRINT N'Adding default constraint...'
GO
ALTER TABLE [dbo].[Contacts]
ADD CONSTRAINT [DF_Address_CreatedDate]
DEFAULT (getdate())
FOR [CreatedDate]
GO
PRINT N'Setting column to NOT NULL'
GO
ALTER TABLE [dbo].[Contacts]
ALTER COLUMN [CreatedDate] [datetime] NOT NULL
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment