通过SQL语句生成日历表格
你还在通过Asp.Net控件或者服务器端语句处理来生成日历表格吗?
或者你还在用客户段javascript来生成日历表格吗?
那么他们生成的表格是不是都是周日排在第一列?
请看我生成的下图:
9年2月份
9年6月份
9年7月份
只是通过一段简单的SQL语句(存储过程),传入时间,输出以星期一打头列的日历表格。
换成这个角度来处理,大家还会不会在C#后台为算出第几星期而伤脑筋?
O(∩_∩)O哈哈~
其实也没有什么,就是一段小小的存储过程,不就是T-SQL嘛,大牛就不要拍砖了。
不过对小虾来讲,确实是实用啊,贴首页了,我脸皮厚,砖头都拍不烂,不信你们试试~
存储过程贴出如下:
Code
-- =============================================
-- Author: chf
-- Create date: 2009-06-25
-- Description: 传入时间,返回当前月份列表
-- =============================================
alter PROCEDURE GetMonthTable
(
@Date datetime
)
AS
BEGIN
DECLARE @Start DATETIME,@End DATETIME
DECLARE @Index INT
SET @Start = DATEADD(MONTH,DATEDIFF(MONTH,0,@Date),0)
SET @End = DATEADD(MONTH,1,@Start)
SET @Index = DATEDIFF(DAY,-1,@Start)%7 - 1;
SET @Start = DATEADD(mm,DATEDIFF(mm,0,@Date),0)
SET @End = DATEADD(mm,1,@Start) - 1
SET @Index= DATEDIFF(day,0,@Start)%7
;WITH temp(date,row,col) AS
(
SELECT date=1,row=@Index/7+1,col=@Index%7+1
UNION ALL
SELECT date=date+1,row=(@Index+date)/7+1,col=(@Index+date)%7+1
FROM temp
WHERE date <= DATEDIFF(DAY,@Start,@End)
)
SELECT ISNULL(CONVERT(CHAR(2),[1]),'') AS 一,
ISNULL(CONVERT(CHAR(2),[2]),'') AS 二,
ISNULL(CONVERT(CHAR(2),[3]),'') AS 三,
ISNULL(CONVERT(CHAR(2),[4]),'') AS 四,
ISNULL(CONVERT(CHAR(2),[5]),'') AS 五,
ISNULL(CONVERT(CHAR(2),[6]),'') AS 六,
ISNULL(CONVERT(CHAR(2),[7]),'') AS 日
FROM temp
PIVOT
(
MAX(date) FOR col IN ([1],[2],[3],[4],[5],[6],[7])
) AS B
END
GO
-- =============================================
-- Author: chf
-- Create date: 2009-06-25
-- Description: 传入时间,返回当前月份列表
-- =============================================
alter PROCEDURE GetMonthTable
(
@Date datetime
)
AS
BEGIN
DECLARE @Start DATETIME,@End DATETIME
DECLARE @Index INT
SET @Start = DATEADD(MONTH,DATEDIFF(MONTH,0,@Date),0)
SET @End = DATEADD(MONTH,1,@Start)
SET @Index = DATEDIFF(DAY,-1,@Start)%7 - 1;
SET @Start = DATEADD(mm,DATEDIFF(mm,0,@Date),0)
SET @End = DATEADD(mm,1,@Start) - 1
SET @Index= DATEDIFF(day,0,@Start)%7
;WITH temp(date,row,col) AS
(
SELECT date=1,row=@Index/7+1,col=@Index%7+1
UNION ALL
SELECT date=date+1,row=(@Index+date)/7+1,col=(@Index+date)%7+1
FROM temp
WHERE date <= DATEDIFF(DAY,@Start,@End)
)
SELECT ISNULL(CONVERT(CHAR(2),[1]),'') AS 一,
ISNULL(CONVERT(CHAR(2),[2]),'') AS 二,
ISNULL(CONVERT(CHAR(2),[3]),'') AS 三,
ISNULL(CONVERT(CHAR(2),[4]),'') AS 四,
ISNULL(CONVERT(CHAR(2),[5]),'') AS 五,
ISNULL(CONVERT(CHAR(2),[6]),'') AS 六,
ISNULL(CONVERT(CHAR(2),[7]),'') AS 日
FROM temp
PIVOT
(
MAX(date) FOR col IN ([1],[2],[3],[4],[5],[6],[7])
) AS B
END
GO