SQL server with方法修改

SQL server with方法修改,SQL 2008 不支持 with方法 需要改写下:

复制代码
WITH MonthsCTE AS (
4		SELECT @StartDate AS MonthStart
5		UNION ALL
6		SELECT DATEADD(month, -1, MonthStart)
7		FROM MonthsCTE
8		WHERE MonthStart > @EndDate
9	)
10
11	INSERT INTO dbo.dim_year_quarter_month ([dt],[year],[quarter],[ym]) 
12	SELECT 
13	    @DateThreshold as dt,
14		DATEPART(YEAR, MonthStart) AS year,
15		DATEPART(QUARTER, MonthStart) AS quarter,
16		CONVERT(varchar(7), MonthStart, 120) as ym
17	FROM MonthsCTE
18	WHERE MonthStart <= @StartDate
19	ORDER BY MonthStart DESC

改为

-- 创建临时表存储结果

CREATE TABLE #TempMonths (

MonthStart DATE

)

-- 使用WHILE循环填充临时表

WHILE @CurrentDate >= @EndDate

BEGIN

INSERT INTO #TempMonths (MonthStart)

VALUES (@CurrentDate);

SET @CurrentDate = DATEADD(month, -1, @CurrentDate);

END

-- 插入新数据

INSERT INTO dbo.dim_year_quarter_month([dt], [year], [quarter], [ym])

SELECT

@DateThreshold as dt,

DATEPART(YEAR, tm.MonthStart) AS year,

DATEPART(QUARTER, tm.MonthStart) AS quarter,

CONVERT(varchar(7), tm.MonthStart, 120) as ym

FROM #TempMonths tm

WHERE tm.MonthStart <= @StartDate

ORDER BY tm.MonthStart DESC

-- 清理临时表

DROP TABLE #TempMonths

相关推荐
DN金猿3 分钟前
接口路径正确,请求接口却提示404
java·tomcat
getapi18 分钟前
注塑件的费用构成
linux·服务器·ubuntu
爱学习的阿磊35 分钟前
使用Fabric自动化你的部署流程
jvm·数据库·python
枷锁—sha41 分钟前
【SRC】SQL注入快速判定与应对策略(一)
网络·数据库·sql·安全·网络安全·系统安全
Maynor99643 分钟前
OpenClaw 玩家必备:用 AI 自动追踪社区最新动态
java·服务器·人工智能
郝学胜-神的一滴1 小时前
深入解析C/S模型下的TCP通信流程:从握手到挥手的技术之旅
linux·服务器·c语言·网络·网络协议·tcp/ip
堕2741 小时前
java数据结构当中的《排序》(一 )
java·数据结构·排序算法
惜分飞1 小时前
ORA-600 kcratr_nab_less_than_odr和ORA-600 4193故障处理--惜分飞
数据库·oracle
chian-ocean1 小时前
CANN 生态进阶:利用 `profiling-tools` 优化模型性能
数据库·mysql
“αβ”1 小时前
数据链路层协议 -- 以太网协议与ARP协议
服务器·网络·网络协议·以太网·数据链路层·arp·mac地址