Question

I need to make conditional requirements for fields. I'm not sure how this looks in SQL. I'm using Management Studio with SQL Server 2008. Essentially I would like a field to become required only when another field has data entered into it. I researched triggers, and I think that's what I need, but I'm not sure what type (DDL, DML, ect.).

For example:

When the user enters a time they must also enter a date, but if no time is entered then no date is required. SQL would send an error and not allow the user to complete the record without entering a date while the time field is filled.

Thanks!

Was it helpful?

Solution

You can use a check constraint.

create table YourTable
(
  ID int identity primary key,
  DateCol date,
  TimeCol time,
  constraint ch_DateTime check(
                              DateCol is not null or 
                              TimeCol is null
                              )
)

Test with this:

-- null in both columns
insert into YourTable default values

-- values in both columns
insert into YourTable(DateCol, TimeCol) values(getdate(), getdate())

-- value only in DateCol
insert into YourTable(DateCol) values(getdate())

-- value only in TimeCol failes
insert into YourTable(TimeCol) values(GetDate())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top