Get a list of dates between two dates using a function

前端 未结 21 1447
天涯浪人
天涯浪人 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:55

    All you have to do is just change the hard coded value in the code provided below

    DECLARE @firstDate datetime
        DECLARE @secondDate datetime
        DECLARE @totalDays  INT
        SELECT @firstDate = getDate() - 30
        SELECT @secondDate = getDate()
    
        DECLARE @index INT
        SELECT @index = 0
        SELECT @totalDays = datediff(day, @firstDate, @secondDate)
    
        CREATE TABLE #temp
        (
             ID INT NOT NULL IDENTITY(1,1)
            ,CommonDate DATETIME NULL
        )
    
        WHILE @index < @totalDays
            BEGIN
    
                INSERT INTO #temp (CommonDate) VALUES  (DATEADD(Day, @index, @firstDate))   
                SELECT @index = @index + 1
            END
    
        SELECT CONVERT(VARCHAR(10), CommonDate, 102) as [Date Between] FROM #temp
    
        DROP TABLE #temp
    

提交回复
热议问题