Check constraints that ensures the values in a column of tableA is less the values in a column of tableB

邮差的信 提交于 2019-12-11 10:18:21

问题


I'm creating a database and i have the tables ProjectDetails.TimeCardExp and ProjectDetails.Project. The TimeCardExp table has a column ExpenseDate, and in the table Project, there is column EndDate; (they both accept the datetime data type). What I want to do is to implement a constraint on the ExpenseDate column of the TimeCardExp table that ensures that the values entered in the ExpenseDate column of table TimeCardExp are less than the values in the EndDate column of the Project table, for the same employee.

TimeCardExp table *TimeCardID*EmployeeID*ProjectID*ExpenseDate

Project table *ProjectID*EmployeeID*EndDate

Above is the two tables and some columns, my task is to make sure values entered in TimeCard.ExpenseDate are always less than the values Project.EndDate, for the same employee. thanks


回答1:


If it is possible to express the condition you want to avoid as a simple join (as seems to be the case here) then you can enforce this declaratively with an indexed view as long as you create a helper table.

CREATE TABLE dbo.TwoRows
  (
     X INT PRIMARY KEY
  );

INSERT INTO dbo.TwoRows
VALUES      (1), (2)

Then you just express the condition that should never occur and cross join that to the helper table.

CREATE VIEW TimeCardExpenseDateLessThanProjectEndDate
WITH SCHEMABINDING
AS
  SELECT P.ProjectID,
         P.EmployeeID,
         P.EndDate,
         TC.ExpenseDate
  FROM   ProjectDetails.Project AS P
         INNER JOIN ProjectDetails.TimeCardExp AS TC
           ON P.ProjectID = TC.ProjectID
              AND P.EmployeeID = TC.EmployeeID
              AND P.EndDate <= TC.ExpenseDate
         CROSS JOIN dbo.TwoRows

GO

CREATE UNIQUE CLUSTERED INDEX IX
  ON TimeCardExpenseDateLessThanProjectEndDate(ProjectID, 
                                               EmployeeID, 
                                               EndDate, 
                                               ExpenseDate) 


来源:https://stackoverflow.com/questions/21197343/check-constraints-that-ensures-the-values-in-a-column-of-tablea-is-less-the-valu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!