Convert ‘datetime’ to ‘datetimeoffset’ in SQL Server (T-SQL Examples)

This article contains examples of converting a datetime value to a datetimeoffset value in SQL Server.

When you convert a datetime value to datetimeoffset, the resulting value will depend on the fractional seconds precision that you assign to datetimeoffset, as well as any time zone offset you specify.

The datetime data type has a maximum of 3 digits for its fractional seconds part. Its accuracy is rounded to increments of .000, .003, or .007 seconds.

The datetimeoffset data type, on the other hand, allows you to specify a fractional seconds precision from 0 to 7. If you don’t specify this, it will use 7 (the default). It also has a time zone offset and can preserve any offsets in the original value. However, datetime has no time zone awareness, so there are no existing values to preserve. In this case, the time zone offset defaults to +00:00.

SQL Server actually has the TODATETIMEOFFSET() function, which is specifically designed to convert a date/time value to datetimeoffset and add a time zone offset. However, there’s a subtle detail to be aware of when using this function, and I explain this below (with examples).

Continue reading

Convert ‘datetime’ to ‘datetime2’ in SQL Server (T-SQL Examples)

This article contains examples of converting a datetime value to a datetime2 value in SQL Server.

When you convert a datetime value to datetime2, the resulting value will depend on the fractional seconds precision that you assign to datetime2.

The datetime data type has a maximum of 3 digits for its fractional seconds part. Its accuracy is rounded to increments of .000, .003, or .007 seconds.

The datetime2 data type, on the other hand, allows you to specify a fractional seconds precision from 0 to 7. If you don’t specify this, it will use 7 (the default).

Continue reading

How to Return a List of Data Types in SQL Server (T-SQL)

If you ever need to get a list of data types in SQL Server, you can use one of the system views to do just that.

In particular, you can use the sys.types system catalog view. This view returns all system-supplied and user-defined data types defined in the database. If you’re using SQL Server 2000 sys.systypes should do the trick.

Continue reading