SQL Server variant from Oracle TZ_OFFSET - sql

The execution of following SQL in Oracle:
SELECT TZ_OFFSET('Europe/Brussels') from dual;
returns the value +02:00
Note that this function can be used for any timezone in Olsson notation. It's not about the database server.
I was wondering if there exists a similar function in MS Sql Server where you can ask the offset of a given timezone (in the microsoft timezone notation).

From SQL 2016 onward, and in Azure SQL Database, you can achieve this with:
SELECT DATENAME(tz, SYSDATETIMEOFFSET() AT TIME ZONE 'Romance Standard Time')
-- Output: '+02:00'
Notice the time zone names are Windows time zone identifiers, not the IANA TZ (aka Olson) identifiers. For more on the differences, see the timezone tag wiki.
If you want to use IANA TZ identifiers, or if you are using an older version of SQL Server that doesn't have the AT TIME ZONE function, then you can use my SQL Server Time Zone Support project, with the following:
SELECT DATENAME(tz, Tzdb.SwitchZone(SYSDATETIMEOFFSET(), 'Europe/Brussels'))
-- Output: '+02:00'
Also, note that an offset can only be computed for a time zone at a particular reference point. In my examples, you can see I have chosen the current system time with SYSDATETIMEOFFSET(). (The current time is implicit with Oracle's TZ_OFFSET function.)

Related

Azure SQL "An error occurred while executing GlobalQuery operation: Encountered an unsupported intrinsic expression AT TIME ZONE."

I have started encountering this error today in an Azure SQL environment. There have been no changes to the Azure SQL environment from our end. No changes to schema objects, resources, etc.
I have two databases on the same azure sql server and this error occurs in any cross-database query, but does not happen within a single database.
For example, this query is successful:
select [LAST_MODIFIED], [LAST_MODIFIED] AT TIME ZONE 'UTC' AT TIME ZONE 'AUS Eastern Standard Time'
from hbm_client --this is a local table in the database
And this query fails:
select [LAST_MODIFIED], [LAST_MODIFIED] AT TIME ZONE 'UTC' AT TIME ZONE 'AUS Eastern Standard Time'
from hbm_client --local table
inner join dbo.Account --table in other database, ignore the invalid join, it's not the cause
Any ideas on what could cause this change in behaviour given there were not database changes?
I had the same problem. For some reason AT TIME ZONE works for a lot of my queries but failed for one of them. I haven't done a deep dive of the problem but I found a fix with TRY_CAST
select TRY_CAST([LAST_MODIFIED] AT TIME ZONE 'UTC' AT TIME ZONE 'AUS Eastern Standard Time' AS DATETIME) as [LAST_MODIFIED]
from ...
You can swap out DATETIME for DATE or TIME if you prefer but if the value cannot be cast it will return null instead of an error

How to get server OS local time in all Postgres versions

How to get server local time in char(8) format hh:mm:ss in every Postgres version.
In 9.1 it works:
select current_time::char(8)
returns proper local time 13:46:00
In 9.5 it returns 3 hour different time:
10:46:00
select current_time, version() returns
"10:48:40.181735+00";"PostgreSQL 9.5.2, compiled by Visual C++ build 1800, 32-bit"
and
"13:48:51.775138+03";"PostgreSQL 9.1.2 on x86_64-unknown-linux-gnu, compiled by gcc-4.4.real (Debian 4.4.5-8) 4.4.5, 64-bit"
Update
Both servers use default postgres.conf settings for time.
postgres.conf does not contain timezone settings.
in 9.5 Windows 10 it contains
#timezone = 'GMT'
#timezone_abbreviations = 'Default'
in 9.1 Debian it contains
#timezone = '(defaults to server environment setting)'
#timezone_abbreviations = 'Default'
How to get server local time in 9.5 when default postgresql.conf file is used ?
It looks like server does not use OS setting in 9.5
How to force 9.5 to ask timezone from OS and return time in this zone?
Ask for the time zone you want:
select current_time at time zone 'brt';
timezone
--------------------
08:26:16.778448-03
If you need a string:
select to_char(current_timestamp at time zone 'brt', 'HH24:MI:SS');
to_char
----------
08:32:07
Notice that the to_char function does not accept the time type. Use timestamp instead.
Get the OS local time zone from the shell. In Linux:
$ date +%Z
BRT
In psql:
=> \! date +%Z
BRT
If there is psql at the client:
psql -c "\! date +%Z" --host localhost --dbname=cpn --no-password
BRT
It is necessary a .pgpass file to avoid supplying the password.
If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone. If TZ is not defined or is not any of the time zone names known to PostgreSQL, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime(). The default time zone is selected as the closest match among PostgreSQL's known time zones. (These rules are also used to choose the default value of log_timezone, if not specified.) source
This means that if you do not define a timezone, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime().
If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone.
I believe you need to remove the # in #timezone = 'GMT'
And replace GMT with '(defaults to server environment setting)'
Because '(defaults to server environment setting)' is undefined and thus the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime().
To obtain the local time calculated with the defined timezone:
select current_time, version();
To obtain the local time calculated with a specified timezone:
select current_time at time zone 'US/Eastern';
To obtain the defined timezone:
SELECT current_setting('TIMEZONE');
To assign the timezone that you want to use:
set timezone='US/Eastern';
You can see the different timezones here

How to know a column store utc time in sql or not

I am working with CDC in sql and we have a table lsn_timeMapping and a column inside this table trans_begintime its type as mentioned in sql is datetime. My question is how can i get to know that whether it stores datetime in utc format or server datetime .
HERE is a flow mentioned in msdn
It would appear that the time is stored based upon the server's locale settings(local timezone). Therefore, it will not be UTC unless the server timezone is set to UTC.
Source: https://connect.microsoft.com/SQLServer/feedback/details/533689/store-utc-in-lsn-time-mapping

SQL Server How to persist and use a time across different time zones

In SQL Server I would like to create a table to save time of an event, and would like to convert it into the timezone of the users choice for display purposes. Let us say that If there was an event that happens in London at 1:00 PM GMT, that would be 8:00 am US EST.
Given This example I would like to create a frame work,
where a user would have an ability to save the event and time (Giving the time zone of the event)
Read Those events, with the time displayed in the time zone of his liking (US EST)
How do I accomplish this in SQL Server.
In SQL Server 2008, use the DATETIMEOFFSET data type which is a DATETIME plus a timezone offset included.
SELECT CAST('2010-11-23 16:35:29+09:00' AS datetimeoffset)
would be Nov 23, 2010, 4:35pm in a +9 hour (from GMT) timezone.
SQL Server 2008 also contains functions and SQL commands to convert DATETIMEOFFSET values from one timezone to another:
SELECT
SWITCHOFFSET(CAST('2010-11-23 16:35:29+09:00' AS datetimeoffset), '+01:00')
would result in:
2010-11-23 08:35:29.0000000 +01:00
Same time, different timezone (+1 hour from GMT)
When you save the data, save the GMT, not the local time for the user (in c# this is DateTime.UtcNow)
In your application logic, record the user's timezone, and translate the GMT time to the user's local time using the timezone offset, at runtime.
The way I've solved a similar problem is to do the following:
The table design is to only store GMT time.
All input goes through a stored proc that requires an input of a timezone offset.
The data request is to a Table-Valued Function, with an input for the timezone offset.

Oracle Timestamp UTC time format

CREATE TABLE DIALOGUE_TABLE(EXPIRE_TIME TIMESTAMP);
Following code snippet is inside stored proc :
PO_EXPIRETIME :- OUT PARAM of procedure a varchar2
SELECT TO_CHAR(SYS_EXTRACT_UTC(EXPIRE_TIME))
INTO PO_EXPIRETIME
FROM DIALOGUE_TABLE;
When I run Stored Proc from server using EXEC and print PO_EXPIRETIME timestamp is proper with UTC format.
But when I call stored procedure from OCCI and client the timestamp recieved is not same but that is the actual timestamp in table not UTC formatted.
Maybe something I am missing but what I don't know?
Is there something in client side I need to do?
If the column is declared as a TIMESTAMP and not, say, a TIMESTAMP WITH TIME ZONE or TIMESTAMP WITH LOCAL TIME ZONE, the timestamp that is stored in the table will not have a time zone component. As a result, SYS_EXTRACT_UTC will convert the timestamp to UTC using the session time zone which is something that is controlled by the client and may be different on different client machines. I suspect that if you run
SELECT SessionTimeZone
FROM dual;
from your OCCI application and from your SQL*Plus session that you will end up with different results which is causing the strings returned to be different.
If you want the string that is returned to be independent of the client machine, I would tend to suggest storing the time zone in the database column. Is changing the schema definition to use a TIMESTAMP WITH TIME ZONE an option? Barring that, you could ensure that every client machine has the same time zone configured and/or run an explicit ALTER SESSION, i.e.
ALTER SESSION
SET time_zone = '-05:00';
in the stored procedure to ensure that the conversion is always done from a particular time zone.