Reputation:
I want to convert my datetime2 column to int for each record. How do I do it without creating a variable?
Examples of my datetime2 field:
2020-03-03 10:17:26.0000000
2020-03-03 10:37:35.0000000
etc...
Upvotes: 1
Views: 3819
Reputation: 354
First of all, you should specify the sql variant you are using.
Assuming Microsoft T-SQL, you can use the builtin function CAST
.
CAST ( expression AS data_type [ ( length ) ] )
In your case, to convert from date to integer, you can simply do:
CAST ( [field to convert] AS int )
Microsoft reference documentation: https://learn.microsoft.com/it-it/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15
EDIT:
As pointed out by @HoneyBadger, the direct conversion is not allowed. Since the data doesn't have fractional seconds, you can first try to convert to datetime
type, and then to int
(this is allowed):
CAST (CAST ([field to convert] AS datetime) AS int)
Upvotes: 1