从T-SQL中的一个星期的数字获取日期 [英] Get dates from a week number in T-SQL

查看:123
本文介绍了从T-SQL中的一个星期的数字获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Microsoft SQL Server中,我有一个周号

 (从DATEPART(wk,datecol))

但我想做的是将其重新转到该周的日期范围。



例如,

  SELECT DATEPART(wk,GETDATE())

产生10.我想从这个数字派生3/1/2009和3/7/2009。 >

这是可能吗?

解决方案

Quassnoi的回答有效,在一天中的日期清理日期的钩子(他的开始周离开你比你需要的一天,如果你在一天中使用一个时间 - 你可以测试使用GETDATE())。



我过去使用过这样的东西:

 code> SELECT 
CONVERT(varchar(50),(DATEADD(dd,@@ DATEFIRST - DATEPART(dw,DATECOL),DATECOL)),101),
CONVERT(varchar 50),(DATEADD(dd,@@ DATEFIRST - DATEPART(dw,DATECOL) - 6,DATECOL)),101)

这样做的另一个好处是,通过使用@@ DATEFIRST,您可以处理非标准周开始日期(默认为星期日,但使用SET @@ DATEFIRST可以更改此选项)。



似乎很疯狂,SQL Server中的简单日期操纵必须是这个奥秘,但你去...


In Microsoft SQL Server, I have a week number

(from DATEPART(wk, datecol)) 

but what I would like to do is turn this back into the date span for that week.

For example,

SELECT DATEPART(wk, GETDATE())

yields 10. I would like to derive 3/1/2009 and 3/7/2009 from this number.

Is this possible?

解决方案

Quassnoi's answer works, but kind of leaves you on the hook for cleaning up the dates if they are dates in the middle of the day (his start of week leaves you one day earlier than you need to be if you use a time in the middle of the day -- you can test using GETDATE()).

I've used something like this in the past:

SELECT 
   CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, DATECOL), DATECOL)), 101),
   CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, DATECOL) - 6, DATECOL)), 101)

A side benefit of this is that by using @@DATEFIRST you can handle nonstandard week starting days (the default is Sunday, but with SET @@DATEFIRST you can change this).

It seems crazy that simple date manipulation in SQL Server has to be this arcane, but there you go...

这篇关于从T-SQL中的一个星期的数字获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆