3

我试图创建一个计算列,但由于其中一个列在另一个表中,我知道我需要创建一个 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)       
4

1 回答 1

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 演示

于 2013-02-25T01:05:47.137 回答