How to write a t-sql to display current month in calendar format?
the output should be like
sun mon tues wed thur fri sat
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 ................
should give the current month calendar
This is what I have so far
declare @start int
declare @day int
declare @space varchar(100)
declare @nodays int
select @start=1
select @space=''
select @nodays=datediff(dd,getdate(),dateadd(mm,1,getdate()))
select @day=case datename(dw,cast(year(getdate()) as varchar(10)) + '-' +cast(month(getdate()) as varchar(10)) + '-' +cast(day(getdate()) as varchar(10))) when 'Sunday' then 1 when 'Monday' then 2 when 'tuesday' then 3 when 'wednesday' then 4 when 'thursday' then 5 when 'friday' then 6 when 'saturday' then 7 end
while(@start<=@nodays)
if(@day=1)
if(len(@space)=0)
select @space=cast(@start as varchar(10))
else
select @space=@space+' '+
case when len(cast(@start as varchar(10)))=1
then ' '
else ''
end +
cast(@start as varchar(10))
else
if(len(@space)=0)
select @space=@space+
replicate(char(10),@start) +
case when len(cast(@start as varchar(10)))=1
then ' '
else ''
end +
cast(@start as varchar(10))
else
select @space=@space+char(10) + case when len(cast(@start as varchar(10)))=1 then ' ' else '' end +cast(@start as varchar(10))
select @start=@start+1
print @space+char(10)
7条答案
按热度按时间aiazj4mn1#
You can change the getdate() to a local declared variable if you like.
ljo96ir52#
select DATEPART(MONTH,getdate())
-- gets month numberselect Datename(month,getdate())
-- gets month name7qhs6swi3#
I don't know what you actually are trying to do here. Printing the calender month with T-SQL is probably not what you want to do.
Here is a query that gives you all dates within the current month as a result set. If you just want the day number of the month (like you did) you can use
datepart(d, [Date])
to get that.Same function but split result to as "calender"
Result
yqlxgs2m4#
Forget your 'procedural code to fabricate a calendar on the fly' approach: SQL is a declarative language so instead think in terms of set-based solutions.
Create a permanent
Calendar
table containing all past and future dates you are likely to ever need (should only amount to mere tens of thousands of rows) then query this table when required usingCURRENT_TIMESTAMP
.See Why should I consider using an auxiliary calendar table?
hs1rzwqc5#
here a link for : Creating a Calendar in a single SQL statement
You could add some clauses to specify the month
63lcw9qa6#
c9x0cxw07#
db<>fiddle