Lấy ra tất cả các ngày giữa 2 ngày được chọn (getAllDaysBetweenTwoDate store procuredure)


02/10/2020- duocnt    919 Views    

MỤC ĐÍCH

 - Lấy ra tất cả các ngày giữa 2 ngày được chỉ định.
 - Trả về 1 table.


T-SQL CODE.

Create PROCEDURE getAllDaysBetweenTwoDate
(
    @FromDate DATETIME,   
    @ToDate DATETIME
)
AS
BEGIN
   
    DECLARE @TOTALCount INT
    SET @FromDate = DATEADD(DAY,-1,@FromDate)
    Select  @TOTALCount= DATEDIFF(DD,@FromDate,@ToDate);
 
    WITH d AS
            (
              SELECT top (@TOTALCount) AllDays = DATEADD(DAY, ROW_NUMBER()
                OVER (ORDER BY object_id), REPLACE(@FromDate,'-',''))
              FROM sys.all_objects
            )
        SELECTAllDays From d
       
    RETURN
END




CÁCH SỬ DỤNG


--Ngày đâu
tiên và ngày cuối của tháng
Declare @firstDayOfMonth Date,@lastDayOfMonth Date
 
--Năm và tháng hiện tại hoặc của tháng được chọn
declare @currentMonth int, @currentYear int
 
declare @monthYear varchar(20)
set @monthYear='2020-09-1'
 
set @currentYear = YEAR(CONVERT(date,@monthYear))
set @currentMonth = MONTH(CONVERT(date,@monthYear))
       --lấy ngày đầu và ngày cuối của tháng được chọn
set @firstDayOfMonth = (SELECT DATEADD(month, DATEDIFF(month, 0, CONVERT(date,@monthYear)), 0))
set @lastDayOfMonth =(SELECT DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, CONVERT(date,@monthYear)) + 1, 0)))
exec getAllDaysBetweenTwoDate @firstDayOfMonth,@lastDayOfMonth



KẾT QUẢ.





Góp ý kiến

;
;