This is what I have done, if there is a better/faster/cleaner way please let me know, also which of the two methods is the most efficient?
Neither one is going to be terribly efficient because you are basically forced to do string manipulations, data type conversions, and date arithmetic. Personally, I would use the last one, but that is merely a preference, my preference.
Interestingly when query displyed on screen in management Studio ExpDate comes back as a Datetime 2014-02-28 00:00:00.000
Whereas FirstMonth and ExpDate are just dates 2014-02-28
Why does that happen?
Let's look at the 2nd column...
DATEADD(mm, DATEDIFF(mm, 0, cast('20'+substring(Expirydate,3,2)+'-'+substring(Expirydate,1,2)+'-01'as DATE))+1, -1) ExpDate,
For clarity, let's replace the cast statement with the data type.
[tt]DATEADD(mm, DATEDIFF(mm, 0, [!]<DateDataType>[/!])+1, -1) ExpDate,[/tt]
Now, let's evaluate the expression in the same order that SQL Server evaluates it.
[tt]DATEADD(mm, [!]DATEDIFF(mm, 0, <DateDataType>)[/!]+1, -1) ExpDate,[/tt]
DateDiff always returns an integer, so we have:
[tt]DATEADD(mm, [!]<Integer>[/!]+1, -1) ExpDate,[/tt]
The 3rd argument for the DateAdd function should be a DateTime or Date. Since you are using -1 (which is an integer), SQL Server will automatically convert this to a DateTime data type based on data type precedence.
If the 3rd argument for DateAdd is a DateTime data type, DateAdd returns a DateTime data type, which explains why you are getting DateTime instead of Date.
The 3rd argument you are using for DateAdd is -1, this represents December 31, 1899, so you could do this instead:
[tt]
DATEADD(mm, DATEDIFF(mm, 0, cast('20'+substring(Expirydate,3,2)+'-'+substring(Expirydate,1,2)+'-01'as DATE))+1, [!]Cast('18991231' As Date)[/!]) ExpDate,
[/tt]
In the 3rd column from your example, you add 1 month to a DATE data type, and then subtract 1 day from a DATE data type, so everything remains as a DATE data type.
I also tried using
DATEADD(mm, 1, cast('20'+substring(Expirydate,3,2)+'-'+substring(Expirydate,1,2)+'-01'as DATE))-1
But that failed with error
Msg 206, Level 16, State 2, Line 1
Operand type clash: date is incompatible with int
which is odd as select getdate()-1 returns yesterdays date
GetDate() returns a DateTime data type, which allows you to use the + and - operators. The Date data type does not support it.
Ex:
Code:
Select Cast(GetDate() As Date)-1
This code above returns an error:
[tt][red]
Msg 206, Level 16, State 2, Line 1
Operand type clash: date is incompatible with int
[/red][/tt]
-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom