SQL Server Check if a datetime is in daylight saving in SQL

dwbf0jvd  于 2023-10-15  发布在  其他
关注(0)|答案(2)|浏览(80)

In C# there is a build in method IsDaylightSavingTime which allows returns a bool value indicating if the date that is being passed falls in the range of daylight saving. I would like to know if there is something similar in SQL.

Thanks in advance.

dfty9e19

dfty9e191#

How about running the CLR on SQL Server and directly leverage the .Net Framework DateTimeOffset type through a CLR scalar-valued function ?

In order to help SQLServer choose the best possible execution plan, do not forget to carefully value the SqlFunction attribute. For instance, if your function only wraps the call to IsDaylightSavingTime, you'd better decorate it this way.

[SqlFunction(
     DataAccess = DataAccessKind.None, 
     SystemDataAccess = SystemDataAccessKind.None,
     IsDeterministic = true,
     IsPrecise = true)]
lawou6xi

lawou6xi2#

I might be a little bit late. But this script worked fine for me:

declare @date datetime = getdate()

declare @IsDaylightSaving bit
declare @tz int = DATEPART(TZOFFSET, @date AT TIME ZONE 'Pacific Standard Time')

set @IsDaylightSaving = case when @tz = -420 then 1 else 0 end
select @IsDaylightSaving

相关问题