On MS SQL, how to create a table that only consists of dates and days of the week?
我需要在 MS SQL 2014 上创建一个显示日期和工作日列的表。它需要从 2014-01-01 开始,最后一天应该是今天。它应该如下所示:
1 2 3 4 5 6 | days_date weekday 2014-01-01 Wednesday 2014-01-02 Thursday 2014-01-03 Friday ... ... 2018-03-06 Tuesday |
我的相关脚本在这里:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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 |
这里出现一些错误:
1 2 3 4 5 6 | 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. |
我应该如何修复脚本?
-- 将遇到以下错误消息:
消息 530,第 16 级,状态 1,第 1 行
声明终止。
在语句完成之前,最大递归 100 已用完。
要克服此错误消息,可以指定 MAXRECURSION 查询提示以将最大递归次数从默认值 100 增加到最大值 1000。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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)
您不能在 Values 中使用 SELECT 语句,而是使用 select 替换值。
如下更改插入查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | ;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) |
您的插入查询中有一些语法错误。
此外,您尝试插入的
试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 |