在MS SQL上,如何创建仅包含一周中的日期和日期的表?

时间:2018-03-06 11:15:45

标签: sql sql-server sql-server-2014

我需要在MS SQL 2014上创建一个表,显示日期和工作日列。它需要从2014-01-01开始,最后一天应该是今天。它看起来应该像下面那样:

   days_date      weekday
   2014-01-01     Wednesday
   2014-01-02     Thursday
   2014-01-03     Friday
   ...            ... 
   2018-03-06     Tuesday

我的相关脚本在这里:

 CREATE TABLE [dbo].[new_table](
     [days_date] [date] NOT NULL,
     [weekday] [nvarchar](50) NULL
 ) ON [PRIMARY]

GO

 WITH CTE (DT) AS 
 (
    SELECT CAST('2014-01-01' AS DATE) DT
    UNION ALL
    SELECT DATEADD(DAY, 1, DT)
    FROM CTE
    WHERE DATEADD(DAY, 1, DT) < '2018-03-06'
 )
 INSERT INTO [dbo].[new_table]
          ([days_date]
          ,[weekday])
 VALUES
       (select * from CTE,
       ,select DATENAME(CTE,GETDATE()))
 GO

在这里遇到一些错误:

 Msg 156, Level 15, State 1, Line 13
 Incorrect syntax near the keyword 'select'.
 Msg 156, Level 15, State 1, Line 14
 Incorrect syntax near the keyword 'SELECT'.
 Msg 155, Level 15, State 1, Line 14
 'CTE' is not a recognized datename option.

我该如何修复脚本?

3 个答案:

答案 0 :(得分:1)

您的插入查询中存在一些语法错误。 此外,您尝试插入的datenamegetdate()有关,我认为这不是您的目标。您应该参考CTE日期别名:DT 试试这个:

CREATE TABLE [dbo].[new_table](
     [days_dates] [date] NOT NULL,
     [weekday] [nvarchar](50) NULL
 ) ON [PRIMARY]

GO

 WITH CTE (DT) AS 
 (
    SELECT CAST('2014-01-01' AS DATE) DT
    UNION ALL
    SELECT DATEADD(DAY, 1, DT)
    FROM CTE
    WHERE DATEADD(DAY, 1, DT) < '2018-03-06'
 )
 INSERT INTO [dbo].[new_table]
          ([days_dates]
          ,[weekday])
       (select * , DATENAME(WEEKDAY,dt) from CTE)
       OPTION (MaxRecursion 0)
 GO

答案 1 :(得分:1)

您不能在值中使用SELECT语句,而是使用select替换值。

更改您的插入查询,如下所示

;WITH CTE 
(
    DT
) AS 
(
    SELECT CAST('2014-01-01' AS DATE) DT
    UNION ALL
    SELECT 
       DATEADD(DAY, 1, DT)
       FROM CTE
          WHERE DATEADD(DAY, 1, DT) < '2018-03-06'
)
INSERT INTO [dbo].[new_table]
(
    [days_date],
    [weekday]
)
select
    DT,
    DATENAME(DW,DT)
    from CTE
OPTION(maxrecursion 0)

答案 2 :(得分:1)

- 将遇到以下错误消息:

Msg 530,Level 16,State 1,Line 1 声明终止。 在语句完成之前,最大递归100已用尽。 要克服此错误消息,可以指定MAXRECURSION查询提示,以将最大递归数从默认值100增加到最大值1000。

 CREATE TABLE [dbo].[new_table](
         [days_date] [date] NOT NULL,
         [weekday] [nvarchar](50) NULL
     ) ON [PRIMARY]

; WITH CTE (DT) AS 
 (
    SELECT CAST('2014-01-01' AS DATE) DT
    UNION ALL
    SELECT DATEADD(DAY, 1, DT)
    FROM CTE 
    WHERE DATEADD(DAY, 1, DT) < =GETDATE()
 )

 INSERT INTO [dbo].[new_table]
          ([days_date]
          ,[weekday])
 SELECT DT,DATENAME(DW,DT)  
 FROM CTE OPTION (maxrecursion 0)

 GO
 SELECT * FROM new_table

- 过来这样的问题使用OPTION(maxrecursion 0)