我正在尝试实施一个图书馆管理数据库,我想根据贷款日期推断一个返回日期,loandays
,它将保留我们允许用户拥有该书的天数。到目前为止,这是我的代码:
CREATE TABLE LOAN
(
COPY_ID int CONSTRAINT LOAN_COPY_FK
FOREIGN KEY(COPY_ID) REFERENCES COPY(COPY_ID) NOT NULL,
BORROWER_ID int CONSTRAINT LOAN_BORROWER_FK
FOREIGN KEY (BORROWER_ID) REFERENCES BORROWER (BORROWER_ID) NOT NULL,
LOAN_DATE DATE NOT NULL CONSTRAINT check_loan_date
CHECK (LOAN_DATE < RETURN_DATE),
LOAN_DAYS int NOT NULL,
RETURN_DATE AS (LOAN_DATE + LOAN_DAYS) CONSTRAINT LOAN_PK
PRIMARY KEY(COPY_ID, BORROWER_ID)
)
我有一个错误,因为LOAN_DAYS
是整数,我不知道如何把它当作没有月份和年份的日期。
答案 0 :(得分:1)
您应该计算RETURN_DATE AS DATEADD(day, LOAN_DAYS, LOAN_DATE)
,并且不能在检查约束RETURN_DATE
中使用计算出的CONSTRAINT check_loan_date CHECK (LOAN_DATE < RETURN_DATE)
。
相反,我建议使用LOAD_DAYS
大于0的检查约束,这可以保证RETURN_DATE
大于LOAD_DATE
,如下所示:
CREATE TABLE LOAN
(
COPY_ID int CONSTRAINT LOAN_COPY_FK FOREIGN KEY(COPY_ID) REFERENCES COPY(COPY_ID) NOT NULL,
BORROWER_ID int CONSTRAINT LOAN_BORROWER_FK FOREIGN KEY (BORROWER_ID) REFERENCES BORROWER (BORROWER_ID) NOT NULL,
LOAN_DATE DATE NOT NULL ,
LOAN_DAYS int NOT NULL CONSTRAINT check_loan_days CHECK (LOAN_DAYS > 0),
RETURN_DATE AS DATEADD(day,LOAN_DAYS,LOAN_DATE) CONSTRAINT LOAN_PK PRIMARY KEY(COPY_ID, BORROWER_ID)
)