I need to convert Datetime fields to a specifically formatted INT type. For example, I want
2000-01-01 00:00:00.000
to convert to 20010101
.
What is the most performant way to make that conversion for comparison in a query?
Something like:
DATEPART(year, orderdate) * 10000 + DATEPART(month, orderdate) * 100 +
DATEPART(day, orderdate)
or
cast(convert(char(8), orderdate, 112) as int)
What's the most performant way to do this?
Method 1: Using multiplication with 100's In this method, we will multiply each component, of the date with multiples of 100 and add them all to convert them into integers.
Assuming you are looking for the "time" analogy to the "date" portion of your code which takes YYYYMMDD and turns it into an INT , you can: start with the HH:mm:ss format given by the style number 108. remove the colons to get that string into HHmmss. then convert that to INT.
The function called "CDate" will convert any value to a date as long as the expression is a valid date. In this example, the variable LDate would now contain the value 4/6/2003.
Use the CONVERT() function to change the format of a date from a given column or expression. This function takes three arguments: The new data type (in our example, NVARCHAR).
Your example of cast(convert(char(8), orderdate, 112) as int)
seems fine to me. It quickly gets the date down to the format you need and converted to an int.
From an execution plan standpoint, there seems to be no difference between the two.
You can try with TSQL builtin functions. It's not .NET tick compatible but it's still FAST sortable and you can pick your GRANULARITY on demand:
SELECT setup.DateToINT(GETDATE(), 4) -- will output 2019 for 2019-06-06 12:00.456
SELECT setup.DateToINT(GETDATE(), 6) -- will output 201906 for 2019-06-06 12:00.456
SELECT setup.DateToINT(GETDATE(), 20) -- will output 20190606120045660 for 2019-05-05 12:00.456
CREATE FUNCTION setup.DateToINT(@datetime DATETIME, @length int)
RETURNS
BIGINT WITH SCHEMABINDING AS
BEGIN
RETURN CONVERT(BIGINT,
SUBSTRING(
REPLACE(REPLACE(
REPLACE(REPLACE(
CONVERT(CHAR(25), GETDATE(), 121)
,'-','')
,':','')
,' ','')
,'.','')
,0
,@length+1)
)
END
GO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With