日期函数返回SQL Server中的空值

时间:2016-02-21 12:17:41

标签: sql sql-server database function date

Create FUNCTION [dbo].[NewFinishDate]
    (@HourlyQ decimal(18,2), @TotalQ decimal(18,2),
     @Monday integer, @Tuesday integer, @Wednesday integer,
     @Thursday integer, @Friday integer, @Saturday integer, @Sunday integer)
RETURNS date
AS
BEGIN
    DECLARE @DayName nvarchar(10), @DayHour integer,
            @Calculation Decimal(18,2), @Date as date,
            @i integer, @Finishdate date, @Addeddate date

    SELECT 
        @Date = DATEADD(DAY, -1, [Starting date]) 
    FROM
        [Quantities&Planning]

    WHILE @Calculation < @TotalQ 
    BEGIN
        SELECT @i += 1

        SELECT @Addeddate = DATEADD(DAY, @i, @date)
        SELECT @DayName = DATENAME(WEEKDAY, @Addeddate) 

        IF @DayName ='Monday' 
        BEGIN
            set @DayHour = @Monday
            set @Calculation += @HourlyQ*@DayHour
        end
        else if @DayName ='Tuesday' 
        begin
            set @DayHour = @Tuesday
            set @Calculation += @HourlyQ*@DayHour
        end

        if @DayName ='Wednesday' 
        begin
            set @DayHour = @Wednesday
            set @Calculation += @HourlyQ*@DayHour
        end
        else if @DayName ='Thursday' 
        begin
            set @DayHour = @Thursday
            set @Calculation += @HourlyQ*@DayHour
        end
        else if @DayName ='Friday' 
        begin
            set @DayHour = @Friday
            set @Calculation += @HourlyQ*@DayHour
        end
        else if @DayName ='Saturday' 
        begin
            set @DayHour = @Saturday
            set @Calculation += @HourlyQ*@DayHour
        end
        else if @DayName ='Sunday' 
        begin
            set @DayHour = @Sunday
            set @Calculation += @HourlyQ*@DayHour
        end         
    end     

    SELECT
        @Finishdate = DATEADD(DAY, @i, [Starting date]) 
    FROM
        [Quantities&Planning]

    RETURN @Finishdate
END

SELECT
    [dbo].[NewFinishDate](2,5000,2,2,2,2,2,2,2) as Yekeee 
FROM
    [Quantities&Planning]

此代码返回NULL值。我有一个[Quantities&Planning]表和[StartingDate]列,其中包含日期类型变量。我还尝试返回另一个变量,例如nvarcharinteger。问题可能在while循环中。

1 个答案:

答案 0 :(得分:2)

您是否意识到以下声明:

SELECT 
    @Date = DATEADD(DAY, -1, [Starting date]) 
FROM
    [Quantities&Planning]

将整个表[Starting date]返回的最后[Quantities&Planning](减去1天)分配给@Date?最后一行甚至是任意的,因为你的select语句中没有ORDER BY子句。

分配给@Finishdate同样的事情......您可能想要从特定行分配,是吗?然后添加一个适当的WHERE子句,仅选择该特定行。

第二个问题,您永远不会初始化@i变量,因此在您运行时它是NULL

SELECT @i += 1

@i将继续NULL整个程序(对NULL作出NULL的操作。)

您继续使用此NULL值添加到日期,这也会产生NULL值。

@Calculation相同的问题...您需要在使用它们之前初始化变量!这不是因为你声明一个变量,它们会自动初始化为0表示整数和小数。它们被初始化为NULL,除非您以不同方式初始化它们。