我困在存儲過程中,我需要一些幫助。我有一個程序,告訴我在兩個日期內有多少個月,每週或每天的日期,但我不知道它是如何計算兩天之間的日差作爲'2015-06-01'和' 2015-06-30'爲此它顯示它是整月或入境是1個月,但'2015-06-01'和'2015-07-01'它顯示1個月和2天。此外,它通過將它們的數字除以7來計算剩餘的幾天,但我想要日曆周。我無法做到這兩件事。需要日曆天的存儲過程幫助
這是代碼 -
CREATE PROCEDURE GetDateParts
(
@StartDate DATE ,
@EndDate DATE
)
AS
BEGIN
/* variables to be used */
DECLARE @Return VARCHAR(5)
/*
Get the difference between the two dates
add 1 to the value to include the first day in the count
*/
, @TotalNumberOfDays INT
, @DaysInMonth TINYINT;
/* table variable to store the number of days in a month
this would be better as a fixed SQL table as it'll
be called a lot */
DECLARE @Months TABLE
([Month] TINYINT, [NoDays] TINYINT);
/* month values */
INSERT INTO @Months
VALUES
(1, 31),
(2, 28),
(3, 31),
(4, 30),
(5, 31),
(6, 30),
(7, 31),
(8, 31),
(9, 30),
(10, 31),
(11, 30),
(12, 31);
/* Create Result table */
DECLARE @ResultTable TABLE ([MonthNumber] TINYINT, [FullMonth] BIT, [Weeks] TINYINT, [Days] TINYINT)
-- set the count as the mointh number
DECLARE @Count TINYINT = MONTH(@StartDate);
SET @TotalNumberOfDays = DATEDIFF(day, @StartDate, @EndDate)+1
WHILE @Count <= MONTH(@EndDate)
BEGIN
/* get the number of days in the month */
SELECT @DaysInMonth = [NoDays] FROM @Months WHERE [Month] = @Count;
/*
Check if it's a leap year and alter the number of days in Febuary to 29
This was taken from https://www.mssqltips.com/sqlservertip/1527/sql-server-function-to-determine-a-leap-year/
*/
IF((SELECT CASE DATEPART(mm, DATEADD(dd, 1, CAST((CAST(@StartDate AS VARCHAR(4)) + '0228') AS DATE)))
WHEN 2 THEN 1
ELSE 0
END) = 1) AND MONTH(@StartDate) = 2
SET @DaysInMonth = 29;
IF (@TotalNumberOfDays >= @DaysInMonth)
BEGIN
INSERT INTO @ResultTable ([MonthNumber], [FullMonth])
VALUES (@Count, 1)
SET @TotalNumberOfDays = @TotalNumberOfDays - (@DaysInMonth-DAY(@StartDate));
SET @StartDate = DATEADD(day, (@DaysInMonth-DAY(@StartDate)+1), @StartDate);
SET @Count = @Count + 1;
END
ELSE IF (@TotalNumberOfDays >= 7)
BEGIN
INSERT INTO @ResultTable ([MonthNumber], [Weeks])
VALUES (@Count, CAST(@TotalNumberOfDays/7 AS INT))
DECLARE @Remainder TINYINT = @TotalNumberOfDays%7;
IF (@Remainder = 0)
BEGIN
SET @Count = @Count + 1;
END
ELSE
BEGIN
SET @TotalNumberOfDays = @Remainder;
END
END
ELSE
BEGIN
INSERT INTO @ResultTable ([MonthNumber], [Days])
VALUES (@Count, @TotalNumberOfDays)
SET @Count = @Count + 1;
END
END;
-- Return Results
SELECT * FROM @ResultTable;
END
誰能幫助,因爲它是對我很重要。 Thnaks提前
可能只是使用函數'datediff(wk,@start,@end)','datediff(dd,@start,@end)'? –
我真的不能使用它,因爲它顯示了一週的差異,即使有4天的日期差異。我只想顯示一週有7天的差異,並且有整整一週,因爲我有數據明智地表示不在分手天數 –
然後使用'datediff(dd,@start,@end)/ 7'作爲周。 –