how to convert all datetime columns in a sql server 2005 express database with data to UTC

孤街醉人 提交于 2019-12-13 01:52:28

问题


background: We recently upgraded to handle UTC. ie., went thru each sp and func and changed the t-sql code to handle utc. For eg., changed getdate() to getutcdate() etc. For new shipments we are good where the db is blank. For our older customers who want to keep their data we need to run a script that will update all the dates to utc. I am about to code in t-sql something like below and want to know if this is best way. Below is pseudo code. thanks

foreach (table in mydb.tables())
{
  foreach (column col in table)
  {
      if (col.type == datetime)
      {
           update table set col = fn_convert_date_to_utc(col)
      }
  }
}

回答1:


Assuming you know the offset between UTC and the timezone the data is stored in, it's pretty simple:

DECLARE @offset INT;
SET @offset = <offset>;
UPDATE table SET col = DATEADD(HOUR, @offset, col);

Note that might be negative or positive, I have no idea which side of Greenwich you are.

Of course this gets more complicated if you are in a timezone that observes daylight saving time; in this case you may need a more expansive solution such as using a calendar table. This is particularly complex if your data extends back before George Bush changed the American DST rules, for example. I do have an article from a long time ago that may be useful; a more recent series is here:

  • Handle conversion between time zones in SQL Server - part 1
  • Handle conversion between time zones in SQL Server - part 2
  • Handle conversion between time zones in SQL Server - part 3

Also if any of your data falls in that window between 12:00 AM and 2:00 AM on a spring forward/fall back day, where I am never sure whether it is right to change it because it's the changeover day or to not change it because it's before 2 AM.



来源:https://stackoverflow.com/questions/6712039/how-to-convert-all-datetime-columns-in-a-sql-server-2005-express-database-with-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!