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

相关推荐
张铁铁是个小胖子2 小时前
redis执行lua脚本的原子性和数据库原子性的区别
数据库·redis·lua
源图客2 小时前
Spark读取MySQL数据库表
数据库·mysql·spark
admiraldeworm3 小时前
Spring Boot + Spring AI 最小可运行 Demo
java·人工智能·ai
chenglin0163 小时前
ES_数据存储知识
java·服务器·elasticsearch
xiucai_cs4 小时前
MySQL深分页慢问题及性能优化
数据库·mysql·性能优化·深分页
当牛作馬4 小时前
ES常用查询命令
数据库·mysql·elasticsearch
fs哆哆4 小时前
在VB.net中一维数组,与VBA有什么区别
java·开发语言·数据结构·算法·.net
johnZhangqi4 小时前
深圳大学-计算机信息管理课程实验 C++ 自考模拟题
java·开发语言·c++
奔跑草-4 小时前
【服务器】Apache Superset功能、部署与体验
运维·服务器·apache·powerbi·superset