Win*_*-10 6 sql t-sql sql-server sql-server-2008
我需要一个选择来返回月份和年份在指定的日期范围内我将输入开始年份和月份,而选择将返回从我输入的日期到今天的月份和年份.
我知道我可以循环执行此操作,但我想知道是否可以在一系列选择中执行此操作?
Year Month
---- -----
2010 1
2010 2
2010 3
2010 4
2010 5
2010 6
2010 7
Run Code Online (Sandbox Code Playgroud)
等等.
Jef*_*den 15
天哪......使用"计数递归CTE"或"rCTE"与使用循环一样糟糕或更差.请参阅以下文章,了解我的原因.
http://www.sqlservercentral.com/articles/T-SQL/74118/
这是一种没有任何RBAR的方法,包括计数rCTE的"隐藏RBAR".
--===== Declare and preset some obviously named variables
DECLARE @StartDate DATETIME,
@EndDate DATETIME
;
SELECT @StartDate = '2010-01-14', --We'll get the month for both of these
@EndDate = '2020-12-05' --dates and everything in between
;
WITH
cteDates AS
(--==== Creates a "Tally Table" structure for months to add to start date
-- calulated by the difference in months between the start and end date.
-- Then adds those numbers to the start of the month of the start date.
SELECT TOP (DATEDIFF(mm,@StartDate,@EndDate) + 1)
MonthDate = DATEADD(mm,DATEDIFF(mm,0,@StartDate)
+ (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1),0)
FROM sys.all_columns ac1
CROSS JOIN sys.all_columns ac2
)
--===== Slice each "whole month" date into the desired display values.
SELECT [Year] = YEAR(MonthDate),
[Month] = MONTH(MonthDate)
FROM cteDates
;
Run Code Online (Sandbox Code Playgroud)
小智 -1
declare @date1 datetime,
@date2 datetime,
@date datetime,
@month integer,
@nm_bulan varchar(20)
create table #month_tmp
( bulan integer null, keterangan varchar(20) null )
select @date1 = '2000-01-01',
@date2 = '2000-12-31'
select @month = month(@date1)
while (@month < 13)
Begin
IF @month = 1
Begin
SELECT @date = CAST( CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,0,@date1))-1),DATEADD(mm,0,@date1)),111) + ' 00:00:00' as DATETIME )
End
ELSE
Begin
SELECT @date = CAST( CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,@month -1,@date1))-1),DATEADD(mm,@month -1,@date1)),111) + ' 00:00:00' as DATETIME )
End
select @nm_bulan = DATENAME(MM, @date)
insert into #month_tmp
select @month as nilai, @nm_bulan as nama
select @month = @month + 1
End
select * from #month_tmp
drop table #month_tmp
go
Run Code Online (Sandbox Code Playgroud)