将两个日期之间的月份列表插入表中

时间:2015-06-23 11:36:00

标签: sql-server

嘿,我希望插入两个日期之间的列表月到第二个表,让它进入其中一个月(使用Select Top 1)但我不知道如何让它插入完整列表

这是我的代码。

    DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME,
        @MonthList as Varchar(50)

SELECT   @StartDate = '20110501'        
        ,@EndDate   = '20110801';

SEt @MonthList = (SELECT  DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate))  FROM    master.dbo.spt_values x WHERE   x.type = 'P'    AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate))
SELECT DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS Month
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'        
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate);

Insert Into Payments_ExpectedPayments(Month)
Values(@MonthList)

2 个答案:

答案 0 :(得分:0)

    DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME,


SELECT   @StartDate = '20110501'        
        ,@EndDate   = '20110801';


Insert Into Payments_ExpectedPayments(Month)
SELECT  DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS Month
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'        
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate);

答案 1 :(得分:0)

您不需要@monthlist变量

 DECLARE @StartDate  DATETIME,
        @EndDate    DATETIME
SELECT   @StartDate = '20110501'        
        ,@EndDate   = '20110801';

INSERT INTO Payments_ExpectedPayments([Month])

SELECT DATENAME(MONTH, DATEADD(MONTH, x.number, @StartDate)) AS [Month]
FROM    master.dbo.spt_values x
WHERE   x.type = 'P'        
AND     x.number <= DATEDIFF(MONTH, @StartDate, @EndDate);