我试图创建一个计算列,但由于其中一个列在另一个表中,我明白我需要创建一个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)
答案 0 :(得分:3)
我认为你的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 Demo