我有以下sql:
;WITH DatesCTE AS
(
SELECT CAST('2016-01-01' AS DATE) AS [workingDays]
UNION ALL
SELECT DATEADD(DAY, 1, workingdays)
FROM DatesCTE
WHERE DATEADD(DAY, 1, workingdays) < '2017-01-01'
)
insert into dbo.tWorkingDays
(date,
CASE ((DATEPART(dw, workingDays) + @@DATEFIRST) % 7) NOT IN (0, 1) when TRUE THEN 1,
ELSE 0
END
)
SELECT *
FROM DatesCTE
WHERE ((DATEPART(dw, workingDays) + @@DATEFIRST) % 7) NOT IN (0, 1)
OPTION (MAXRECURSION 366)
和下表:
CREATE TABLE [dbo].[tWorkingDays]
(
[date] [date] NOT NULL,
[is_business_day][bit] NOT NULL DEFAULT 1,
CONSTRAINT [PK_tWorkingDays]
PRIMARY KEY CLUSTERED ([date] ASC)
) ON [PRIMARY]
当我尝试执行请求时,我会看到以下内容:
Msg 156,Level 15,State 1,Line 14
关键字&#39; CASE&#39;附近的语法不正确。
我做错了什么?
答案 0 :(得分:1)
看起来你得到的字段列表(你要插入的字段)与选择列表(你要插入的值)混在一起。它应该是这样的:
;WITH DatesCTE
AS (
SELECT CAST('2016-01-01' AS DATE) AS [workingDays]
UNION ALL
SELECT DATEADD(DAY, 1, workingdays)
FROM DatesCTE
WHERE DATEADD(DAY, 1, workingdays) < '2017-01-01'
)
insert into dbo.tWorkingDays
(date, is_business_day)
SELECT workingDays,
CASE WHEN ((DATEPART(dw, workingDays) + @@DATEFIRST) % 7) NOT IN (0, 1) THEN 1 ELSE 0
END
FROM DatesCTE
WHERE ((DATEPART(dw, workingDays) + @@DATEFIRST) % 7) NOT IN (0, 1)
OPTION (MAXRECURSION 366)
您可能不希望在同一查询中使用WHERE子句和CASE,但引用的代码至少应解决语法错误。
答案 1 :(得分:1)
;WITH DatesCTE AS (
SELECT CAST('20160101' AS DATE) AS [workingDays]
UNION ALL
SELECT DATEADD(DAY, 1, workingdays)
FROM DatesCTE
WHERE DATEADD(DAY, 1, workingdays) < '2017-01-01'
)
INSERT INTO dbo.tWorkingDays (date, is_business_day)
SELECT *, CASE WHEN (DATEPART(dw, workingDays) + @@DATEFIRST) % 7 NOT IN (0, 1) THEN 1 ELSE 0 END
FROM DatesCTE
--WHERE (DATEPART(dw, workingDays) + @@DATEFIRST) % 7 NOT IN (0, 1)
OPTION (MAXRECURSION 366)