Euro Pe
Euro Pe

Reputation: 73

SQL Server - computed date column

I want to create 'Conferences' table and set EndDate as StartDate + ConferenceDays. Is there any way how to do that?

create table Conferences(
    ConferenceID int not null primary key,
    ConferenceName varchar(50) not null,
    ConferenceDays int not null,
    StartDate date not null,
    EndDate date not null,
)

Upvotes: 0

Views: 4660

Answers (2)

Yashveer Singh
Yashveer Singh

Reputation: 1977

For SQL server:

create table Conferences(
    ConferenceID int not null primary key,
    ConferenceName varchar(50) not null,
    ConferenceDays int not null,
    StartDate date not null,
    EndDate AS (dateadd(day,ConferenceDays, StartDate)) PERSISTED
)

Upvotes: 4

Sandy Gettings
Sandy Gettings

Reputation: 713

I suggest rethinking this a little. If EndDate is always StartDate + ConferenceDays, then you essentially have redundant data and that could be considered a violation of normalization rules.

If you're using an ORM or you've defined some class that represents the data table, then I suggest adding a property like this:

partial class Conference {

   DateTime EndDate { get { return this.StartDate.AddDays( this.ConferenceDays ); } }
   ... etc.
}

Will this work for you?

Upvotes: 0

Related Questions