Search code examples
sqlsql-serverformuladatediff

SQL Server : Computed Column DATEDIFF Clause


What I'm trying to do is the following: I have 3 columns (Control_OpenDate, Control_Record Age, Control_Stage2). Once the row is inserted it will populate Control_OpenDate (01/27/2013) and Control_RecordAge (computed column, see formula).

(datediff(day, [Control_OpenDate], getdate()))

which gives the days up to date.

Everything is working perfect but I want to add like an IF condition to the computed column whenever the column Control_Stage2 is populated if not, do not calculate or add a text...

How can I add the WHERE-statement in the above formula??

Note: I'm entering such formula directly into the column properties, I know there are queries that can do this but is there a way to do it trough a formula.


Solution

  • This can be done using a CASE-statement, as shown here.

    Your logic will then look like:

    (CASE 
        WHEN [Control_Stage2] IS NULL THEN NULL -- or -1 or what you like
        ELSE datediff(day,[Control_OpenDate],getdate())
    END)