SQL Server – Calculated Field Updating Every Row Issue

computed-columndefault valuesql serversql-server-2008-r2t-sql

I added a calculated field to my table, and only want to update NULL rows (or "new" rows). Something is going awry, and every row in my table is being updated with the current DateTime when 1 row is inserted. This is the Create Table syntax, what must I do so that only the "new" rows are updated with the current DateTime

CREATE TABLE [dbo].[SE](
[dbID] [int] IDENTITY(1,1) NOT NULL,
[uqID] [varchar](31) NOT NULL,
[POD] [varchar](255) NULL,
[EC] [varchar](255) NULL,
[S1] [varchar](35) NULL,
[S2] [varchar](35) NULL,
[S3] [varchar](35) NULL,
[S4] [varchar](35) NULL,
[S5] [varchar](35) NULL,
[S6] [varchar](35) NULL,
[S7] [varchar](35) NULL,
[PSD] [varchar](50) NULL,
[DS] [datetime] NULL,
[CN] [varchar](max) NULL,
[autodate]  AS (getdate()),
PRIMARY KEY CLUSTERED 
(
[dbID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,     ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Best Answer

You don't want a calculated column, instead just use a datetime (non-nullable) column, with a default constraint using getdate().

The syntax for the column in the table definition SQL is as follows:

[autodate] DATETIME NOT NULL DEFAULT(GETDATE())

A Computed Column in SQL Server is calculated when it is queried (unless it is PERSISTED, then it has a value stored on disk and can be indexed, however it is still computed). It is intended to be changeable, and be the result of calculations on another column or columns.

A DEFAULT Constraint simply inserts a default value into the column for any inserts, but then it is held as a fixed value just like any other data column.