Implicit Time Conversions – #SQLNewBlogger

Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

I was trying to work with times recently and needed to get the current time. I thought, well, Getdate(), or better yet, SysDateTime() will give me a date and time, but what about the time?

A simple experiment showed it’s easy:

DECLARE
    @t TIME,
    @t1 TIME;
SELECT @t = SYSDATETIME(), @t1 = GETDATE();
SELECT @t, @t1;

I got this:

2017-02-24 12_34_19-SQLQuery2.sql - (local)_SQL2016.PartsUnlimited_Grant (PLATO_Steve (59))_ - Micro

Quick, easy, and what I suspected would work. If you need to work with times, you can easily cast a datetime value to a TIME to strip the date, or just assign the values to a time.

CREATE TABLE TimeTest
(t TIME)
GO
INSERT TimeTest
SELECT top 10
 CreationDate
 FROM dbo.Posts
 GO
 SELECT top 10
  *
  FROM dbo.TimeTest
GO
DROP TABLE TimeTest

This code takes a datetime column and just inserts the time into the new table.

SQLNewBlogger

Literally about 3 minutes of my day to write this. When you learn something, write it down.

About way0utwest

Editor, SQLServerCentral
This entry was posted in Blog and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s