How to calculate the local datetime from a utc datetime in tsql (sql 2005)?

前端 未结 10 1342
Happy的楠姐
Happy的楠姐 2021-02-02 14:13

i want to loop over a period of time in tsql, and print the utc datetimes and our local variant. We live in UTC +1, so i could easily add 1 hour, but in the summertime we live i

10条回答
  •  遥遥无期
    2021-02-02 15:07

    Assuming you are using SQL 2005 upwards, you can develop a SQL CLR function to take a UTC date and convert to the local date.

    This link is an MSDN How-To explaining how you can create a scalar UDF in C#.

    Create a SQL function along the lines of

    [SqlFunction()]
    public static SqlDateTime ConvertUtcToLocal(SqlDateTime utcDate) 
    {
        // over to you to convert SqlDateTime to DateTime, specify Kind
        // as UTC, convert to local time, and convert back to SqlDateTime
    }
    

    Your sample above would then become

    set @localdate = dbo.ConvertUtcToLocal(@utcdate)
    

    SQL CLR has its overheads in terms of deployment, but I feel cases like this are where it fits in best.

提交回复
热议问题