Pass a column as parameter to dateadd in SQL Server

邮差的信 提交于 2019-12-10 11:53:10

问题


I want to convert a column of UTC time to local time.

My data looks like this:

time_utc                TZID            timezone
------------------------------------------------
2014-02-27 12:00:39.0   America/Toronto     -5
2013-05-21 09:35:30.0   America/Goose_Bay   -4
2015-01-08 06:58:58.0   America/Creston     -7

I know that using

select *, DATEADD(hour, 5,time_utc)
from mytable

will add 5 hours to column time_utc.

However, as you can see, I have a variable time zone column.

How can I pass this variable to the dateadd function?

I tried the following 2 commands but they don't work:

Attempt #1:

select *, DATEADD(hour, timezone, time_utc)
from mytable

Attempt #2:

select *, DATEADD(hour, (select timezone from mytable), time_utc)
from mytable

Both throws this error:

Argument data type varchar is invalid for argument 2 of dateadd function. [SQL State=S0001, DB Errorcode=8116]

For decimal values of timezone, for instance -3.5, how would this work?

Thanks


回答1:


How can I pass this variable to datetime function?

Just reference the column in the function call:

select *, DATEADD(hour, timezone, time_utc)
from mytable

For decimal values of timezone, for instance -3.5, how would this work?

The "number" parameter of DATEADD takes an integer, so you'd have to change to minutes and scale the hour offset. Since your timezone colume is apparently a varchar column, convert it to a decimal value as well:

select *, DATEADD(minute, cast(timezone as decimal(4,2)) * 60 , time_utc)
from mytable



回答2:


There is a character value (most probably blank) in your dataset. Sql does implicity conversion but for non numeric value it will fail. Check your table to see if you have blanks or non numeric values for timezone



来源:https://stackoverflow.com/questions/34732183/pass-a-column-as-parameter-to-dateadd-in-sql-server

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