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]
列,其中包含日期类型变量。我还尝试返回另一个变量,例如nvarchar
和integer
。问题可能在while循环中。
答案 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
,除非您以不同方式初始化它们。