I have an old table with a few rows that has a datetime column. I want to switch this to datetimeoffset but i want to be able to transfer the data that already exists. So I'm doing something like:
SET IDENTITY_INSERT Table_Temp ON
INSERT INTO Table_Temp
(Col0, ... ColN,)
SELECT
COl0,.... ColN, from
Table_Original;
SET IDENTITY_INSERT Table_Temp OFF
This works but the offset set is 0 when i do the dattime to datetimeoffset assignment. Fortunately the offset that i want to set it to is the offset of the current system. I'm no tsql guru but i can't seem to figure out an easy way to do this.
I want to be able to set the offset within the conversion. I was going to resort to doing a c# utility(or PowerShell) but i would rather keep it simple.
If you're using a version of SQL Server that knows of the datetimeoffset type, this syntax will work for getting you the local tz offset of the server:
select datepart(tz,sysdatetimeoffset())
The result is in MINUTES.
You can figure out what the offset of the current SQL server is using the following.
You need to get the offset in minutes and not hours since there are a number of half hour and even a quarter hour time zone.
Using the minutes value, you can alter your values going in (assuming they were historically all recorded as local time) by using something like
For efficiency I would calculate it once into a variable and use that, since the difference is not going to change.
These conversions functions will not work correctly if DST saving is active in the target timezone, as the timezone offset changes inside the same year.
See below for doc, you probably want something like:
From MSDN
For anyone trying to solve this problem correctly, accounting for DST here is the tool to do it.
https://github.com/mj1856/SqlServerTimeZoneSupport
This is a slight variation of an answer already provided, and does NOT account for DST changes. However, it might be good enough for many purposes: