Best Practices for Computed Column in SQL Server Best Practices for Computed Column in SQL Server sql-server sql-server

Best Practices for Computed Column in SQL Server


Seeing that this date most likely will never change once it's set, it's probably not a good candidate for a computed column.

After all: once you insert a row into that table, you can easily calculate that "end of probation period" date right there and then (e.g. in a trigger), and once set, that date won't ever change.

So while you can definitely do it this way, I would probably prefer to use a AFTER INSERT trigger (or a stored procedure for the INSERT operation) that just calculates it once, and then stores that date.

Also, just as a heads-up: a computed column with just the formula is being calculated every time to access it - just be aware of that. That is, unless you specify the PERSISTED keyword, in that case, the result is stored along side the other data in the row, and this would be a much better fit here - again, since that value, once calculated, is not bound to change ever again.


If you want to later extend someone's probation period without having to change their application date, then a computed column is NOT the way to go. Why not just use a DEFAULT constraint for both columns?

USE tempdb;GOCREATE TABLE dbo.foo(  MemberID INT IDENTITY(1,1),  JoinDate DATE NOT NULL DEFAULT SYSDATETIME(),  ProbationEndDate NOT NULL DEFAULT     DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH,0,SYSDATETIME())+3, 0)));INSERT dbo.foo DEFAULT VALUES;SELECT MemberID, JoinDate, ProbationEndDate FROM dbo.foo;

Results:

MemberID    JoinDate      ProbationEndDate--------    ----------    ----------------1           2013-04-05    2013-06-30

(Notice I used a slightly less convulted approach to get the end of the month for two months out.)


There's no overhead when you insert data; only when you read the column the values are computed for this column. So I'd say your approach is correct.