我试图创建一个计算列,但是由于该列中的一个在另一个表中,所以我知道我需要创建一个udf。这是ERD的链接,因此您可以看到它们之间的关系
http://imageshack.us/photo/my- images/23/databaseassignment2new.png/
这就是我想做的。
CheckOutDate + loanperiod = lastreturndate So the result would look something like this Checkoutdate loanperiod lastreturndate 2012-1-01 3 2012-4-01
这是我到目前为止所拥有的
CREATE FUNCTION dbo.Getvaludates( @laastreturndate DATETIME) RETURNS DATETIME AS BEGIN DECLARE @lastReturndate DATETIME SELECT @lastReturndate= dateadd(month,loanperiod,CheckOutDate) FROM [Loan] I JOIN [Item] L ON I.barcode = L.barcode JOIN [Return] R ON I.barcode = R.barcode WHERE I.barcode = @lastreturndate RETURN @lastReturndate END GO
然后我需要将其添加到计算列
ALTER TABLE dbo.Item ADD lastreturndate AS dbo.Getvaluedate(lastreturndate)
我认为您的UDF应该如下所示:
CREATE FUNCTION dbo.Getvaluedate( @barcode int) RETURNS DATETIME AS BEGIN DECLARE @lastReturndate DATETIME SELECT @lastReturndate= dateadd(month,loanperiod,CheckOutDate) FROM [Loan] I JOIN [Item] L ON I.barcode = L.barcode JOIN [ItemDetails] ID ON L.isbn = ID.isbn WHERE I.barcode = @barcode RETURN @lastReturndate END ;
接着:
ALTER TABLE Loan ADD lastreturndate AS dbo.Getvaluedate(barcode);
这是一个SQL Fiddle演示