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

相关推荐
五岳20 小时前
分库分表数据源ShardingSphereDataSource的Connection元数据误用问题分析
java·mysql·爬坑
带刺的坐椅20 小时前
迈向 MCP 集群化:Solon AI (支持 Java8+)在解决 MCP 服务可扩展性上的探索与实践
java·ai·llm·solon·mcp
悄悄敲敲敲20 小时前
MySQL表的约束
数据库·mysql
鼠爷ねずみ20 小时前
SpringCloud前后端整体开发流程-以及技术总结文章实时更新中
java·数据库·后端·spring·spring cloud
代码or搬砖21 小时前
String字符串
android·java·开发语言
九皇叔叔21 小时前
MySQL 数据库 Read View 详解
数据库·mysql·mvcc·read view
Elastic 中国社区官方博客1 天前
Elasticsearch:圣诞晚餐 BBQ - 图像识别
大数据·数据库·elasticsearch·搜索引擎·ai·全文检索
cui_win1 天前
Prometheus实战教程 - Redis 监控
数据库·redis·prometheus
AM越.1 天前
Java设计模式详解--装饰器设计模式(含uml图)
java·设计模式·uml