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

相关推荐
学习3人组12 分钟前
JVM GC长暂停问题排查
java
Linux-palpitate18 分钟前
Keepalived+LVS实现LNMP网站的高可用部署
linux·运维·服务器·mysql·lvs
R_AirMan24 分钟前
深入浅出Redis:一文掌握Redis底层数据结构与实现原理
java·数据结构·数据库·redis
Hello.Reader38 分钟前
RedisJSON 内存占用剖析与调优
数据库·redis·缓存
人生在勤,不索何获-白大侠43 分钟前
day17——Java集合进阶(Collections、Map)
java·开发语言
FileLink跨网文件交换1 小时前
跨网文件交换?内外网文件交换十大方法构建安全合规的数据传输通道
运维·服务器·网络
️️(^~^)1 小时前
静态路由综合配置实验报告
服务器·网络·计算机网络·智能路由器
程序员小羊!1 小时前
Java教程:JavaWeb ---MySQL高级
java·开发语言·mysql
白仑色1 小时前
Spring Boot 多环境配置详解
java·spring boot·后端·微服务架构·配置管理
超级小忍1 小时前
在 Spring Boot 中优化长轮询(Long Polling)连接频繁建立销毁问题
java·spring boot·后端