change the value of computed column in specific conditions

我的未来我决定 提交于 2019-12-24 14:25:15

问题


I have a table for Library Circulation that have a column named "Delay". This column is a computed column, but it should be changed until the "IsReturned" (another column in this table which is bit) is equal to 0. This means that the delay value should changed and be higher until the member return the book into the library. How can i make this computed column formula ? I try this but it is not a valid formula :

dbo.CalculateDelay(Id,IsReturned,Delay)

and the function was like that :

CREATE FUNCTION CalculateDelay
(
  @Id INT ,
  @IsReturned BIT ,
  @LastDelay INT
)
RETURNS INT
AS
BEGIN
    IF ( @IsReturned = 0 )
        BEGIN
            DECLARE @delay INT = ( SELECT   ( DATEDIFF(minute,
                                                       DATEADD(day, [Time],
                                                          [StartDate]),
                                                       GETDATE()) )
                                   FROM     dbo.Circulation
                                   WHERE    Id = @Id
                                 )
            IF ( SQL_VARIANT_PROPERTY(@delay, 'BaseType') = 'int' )
                BEGIN
                    RETURN @delay
                END
            ELSE
                BEGIN
                    RETURN -5
                END
        END
    RETURN @LastDelay
END

as you understand, The "Delay" column should not change when the "IsReturned" column is equal to 1 (I need to keep the delay in the database).

UPDATE :

I use this code for executing the function and it is working correctly :

DECLARE @g INT 
EXEC @g = dbo.CalculateDelay 15 ,0 ,12000
SELECT @g

Is my code in the formula column incorrect ? or why it has error ?


回答1:


Referring to a computed column in a computed column definition is not allowed. You need to record the times that the item is checked out and returned rather than using a BIT field. You can use those values to define your computed column. For example:

CREATE TABLE Checkouts
(
    CheckoutId INT IDENTITY NOT NULL PRIMARY KEY, 
    CheckedOut DATETIME NOT NULL DEFAULT (getdate()), 
    CheckedIn DATETIME NULL, 
    DelayDays AS (datediff(day, CheckedOut, COALESCE(CheckedIn, getdate()))) 
) 


来源:https://stackoverflow.com/questions/27722749/change-the-value-of-computed-column-in-specific-conditions

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