SQL Server Performance

Conditional Not Null Field

Discussion in 'SQL Server 2008 General DBA Questions' started by danny123, Feb 22, 2011.

  1. danny123 New Member

    How can i create a field in table which can not be null if the Field2 in the same table is not Null.

    Thanks in advance!
  2. FrankKalis Moderator

    You can create a CHECK constraint for that. So, something along the lines of
    ALTER TABLE ... ADD CONSTRAINT... CHECK ((field IS NOT NULL AND Field2 IS NOT NULL)= OR (Field2 IS NULL))
    Now the constraint would check that either in both columns there are values or there is not value in Field2. You might have to adjust the constraint and specify whether in such cases there also should be no value in field or not.
    EDIT: Added missing bracket
  3. danny123 New Member

    Thanks, this was helpful.

Share This Page