Situation
I am trying to construct a query, using a column name: TxnDate (TransactionDate) which is of type INT
. Typical dates look something like this:YYYYMMDD
, so 20180209
or 20171025
as examples. I am unablt to change this fact, otherwise many things will break. It is stuck in this stupid format, unfortunately.
However, it is only useful to me as the data type DATE
, so I must first convert it in a roundabout way: CONVERT(DATE, CONVERT(char(8), TransactionDate))
And to further complicate things, some of the dates are null, negative, or zero, for various reasons. So in order to get it in a usable form, I need to check to make sure that it can be converted:
CASE WHEN ISDATE(TxnDate)=1
THEN CONVERT(DATE, CONVERT(CHAR(8),TxnDate))
END
The records with bad date data are of no use to me.
The problem is that I need do check and then convert this in many different places in the WHERE
statement. This has ballooned my query to slightly ridiculous proportions. I would appreciate some wisdom on a cleaner and more succinct manner of proceeding.
What I have Considered
I am reluctant to add things to the schema, but will do so if it is the better option:
1) Creating a view, which casts for me, and which I can query from, in place of the table, as demonstrated here: Is it possible to change the datatype of a column in a view? I am not partial to this, as there may be problems when attempting to cast, which invalidates the whole purpose.
2) Creating a user defined function which just runs the CASE
expression when called.
3) I have tried many different variations of aliases for variables, and using the AS
expression in many different ways to try and define it in one place only, but to no avail. It might be possible, but I have not been able to find it by either my own efforts or by internet search.
Again, I would appreciate any wisdom on this matter, I am new to SQL, so if there is an obvious solution, or a duplicated question, please point it out. Further, if you feel something is wrong about this question, I would prefer if you were to tell me what was incorrect, before down-voting so I get a chance to improve and learn.
Thank you