SQL Server 某些條件下求某日的日期

來源:互聯網
上載者:User
server|條件

/*需要得結果: 某一天的日期
已知條件: 這天的年,月,星期幾,在這個月中處於第幾周

舉例說明:  希望求出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)



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.