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

相关推荐
apocelipes2 小时前
golang unique包和字符串内部化
java·python·性能优化·golang
Full Stack Developme3 小时前
java.text 包详解
java·开发语言·python
fruge3 小时前
Ubuntu服务器已下载Nginx安装包的安装指南
服务器·nginx·ubuntu
刘梦凡呀4 小时前
C#获取钉钉平台考勤记录
java·c#·钉钉
盒马coding4 小时前
第19节-非规范化数据类型-Composite-types
数据库·postgresql
best_virtuoso4 小时前
PostgreSQL 常见数组操作函数语法、功能
java·数据结构·postgresql
yudiandian20144 小时前
02 Oracle JDK 下载及配置(解压缩版)
java·开发语言
-雷阵雨-4 小时前
MySQL——桥梁JDBC
数据库·mysql·oracle
亿坊电商4 小时前
在PHP框架里如何进行数据库连接?
数据库·oracle·php
孤独得猿4 小时前
聊天室项目开发——etcd的安装和使用
linux·服务器·c++·etcd