当前位置: 首页 > 图文教程 > 数据库 > MSSQL > SQL Server 某些条件下求某日的日期

MSSQL
用SQL Server为Web浏览器提供图像(三)(转)
用SQL Server为Web浏览器提供图像(四)(转)
数据库连接范例
数据访问-与数据库建立连接
SQL Server静态页面导出技术1
SQL Server静态页面导出技术2
Access数据库安全的几个问题
保护Access 2000数据库的安全
ACCESS97关于数据库安全的几个问题
如何把access转换到mysql
将Access数据转换为XML格式
通过Access从Web获取MySQL数据
如何将Access和Excel导入到Mysql中之一
如何将Access和Excel导入到Mysql中之二
如何将Access和Excel导入到Mysql中之三
ACCESS数据库向MySQL快速迁移小程序(一)
ACCESS数据库向MySQL快速迁移小程序(二)
长期使用中型Access数据库的一点经验
微软SQL Server 2005的30项顶尖特性
SQL Server2000企业版安装教程

MSSQL 中的 SQL Server 某些条件下求某日的日期


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-30   浏览: 73 ::
收藏到网摘: n/a

 

/*需要得结果: 某一天的日期
已知条件: 这天的年,月,星期几,在这个月中处于第几周

举例说明:  希望求出2004-11-22
已知条件: 2004年,  11 月,  星期一 ,这天在11月是第四周

declare @year numeric(4),@month numeric(2),@weekday varchar(6),@week numeric(1)
set @year=2004
set @month=11
set @weekday='星期一'
set @week=4
*/

alter function RequestDate
 (@year numeric(4),@month numeric(2),@weekday varchar(6),@week numeric(1))
returns datetime as 
begin

declare @date1 varchar(10) --得到该月的第一天的日期
declare @month1 varchar(2)

if @month<10
 set @month1='0'+ltrim(rtrim(str(@month)))
else
 set @month1=ltrim(rtrim(str(@month)))

set @date1=ltrim(rtrim(str(@year))) + '-' + @month1+ '-' + '01'

declare @num1 numeric(3)
declare @num2 numeric(3)
declare @num3 numeric(3)
set @num1=datepart(ww,@date1)  --得到该月的第一天在该年的周数
set @num1=@num1+@week-2 --得到该月的要求得的那天所在的周数与该年的第一周第一天的周数差

set @num2=datepart(dw,dateadd(ww,@num1,'2004-01-01')) --得到日期对应的星期代号

select @num3=case @weekday
 when '星期日' then 1
 when '星期一' then 2
 when '星期二' then 3
 when '星期三' then 4
 when '星期四' then 5
 when '星期五' then 6
 when '星期六' then 7
end

return dateadd(dd,@num3-datepart(dw,dateadd(ww,@num1,'2004-01-01')),dateadd(ww,@num1,'2004-01-01'))

end


--  select dbo.RequestDate(2004,11,'星期一',4)