Get a list of dates between two dates using a function

前端 未结 21 1073
天涯浪人
天涯浪人 2020-11-22 06:25

My question is similar to this MySQL question, but intended for SQL Server:

Is there a function or a query that will return a list of days between two dates? For exa

21条回答
  •  旧巷少年郎
    2020-11-22 06:50

    Definately a numbers table, though tyou may want to use Mark Redman's idea of a CLR proc/assembly if you really need the performance.

    How to create the table of dates (and a super fast way to create a numbers table)

    /*Gets a list of integers into a temp table (Jeff Moden's idea from SqlServerCentral.com)*/
     SELECT TOP 10950 /*30 years of days*/
            IDENTITY(INT,1,1) as N
       INTO #Numbers
       FROM Master.dbo.SysColumns sc1,
            Master.dbo.SysColumns sc2
    
    
    /*Create the dates table*/
    CREATE TABLE [TableOfDates](
        [fld_date] [datetime] NOT NULL,
     CONSTRAINT [PK_TableOfDates] PRIMARY KEY CLUSTERED 
    (
        [fld_date] ASC
    )WITH FILLFACTOR = 99 ON [PRIMARY]
    ) ON [PRIMARY]
    
    /*fill the table with dates*/
    DECLARE @daysFromFirstDateInTheTable int
    DECLARE @firstDateInTheTable DATETIME
    
    SET @firstDateInTheTable = '01/01/1998'
    SET @daysFromFirstDateInTheTable = (SELECT (DATEDIFF(dd, @firstDateInTheTable ,GETDATE()) + 1))
    
    INSERT INTO
          TableOfDates
    SELECT 
          DATEADD(dd,nums.n - @daysFromFirstDateInTheTable, CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)) as FLD_Date
    FROM #Numbers nums
    

    Now that you have a table of dates, you can use a function (NOT A PROC) like KM's to get the table of them.

    CREATE FUNCTION dbo.ListDates
    (
         @StartDate    DATETIME  
        ,@EndDate      DATETIME
    )
    RETURNS
    @DateList table
    (
        Date datetime
    )
    AS
    BEGIN
    
    /*add some validation logic of your own to make sure that the inputs are sound.Adjust the rest as needed*/
    
      INSERT INTO
        @DateList
      SELECT FLD_Date FROM TableOfDates (NOLOCK) WHERE FLD_Date >= @StartDate AND FLD_Date <= @EndDate
      RETURN
    END
    

提交回复
热议问题