Brian Pringle
asked on
MS-SQL Compare Date Fields of Different Data Type
I have a Microsoft SQL database that imports a CSV file into a table daily. All of the fields in the database have a data type of nvarchar(max) and the fields in the CSV are all strings (enclosed in double quotes).
There is a field in the CSV file -- invoice_date -- that is the date that an item was created. It is in the format of mm/dd/yyyy, but single digit months and days do not have a leading zero.
In the database table, there is another field -- import_date -- that is the date that the CSV was imported and it is formatted as yyyy-mm-dd hh:mm:ss.ssss .
I need to be able to compare these fields against today's date and also against the date of ten days ago.
I need a query that does the following.
select *
from import_table
where import_date = cast(getdate() as date)
and invoice_date <is less than 10 days old>
I tried to convert and cast the invoice_date and the getdate() function in that last line, but it gets an error attempting to convert the string to a date. What is the easiest way to accomplish this?
There is a field in the CSV file -- invoice_date -- that is the date that an item was created. It is in the format of mm/dd/yyyy, but single digit months and days do not have a leading zero.
In the database table, there is another field -- import_date -- that is the date that the CSV was imported and it is formatted as yyyy-mm-dd hh:mm:ss.ssss .
I need to be able to compare these fields against today's date and also against the date of ten days ago.
I need a query that does the following.
select *
from import_table
where import_date = cast(getdate() as date)
and invoice_date <is less than 10 days old>
I tried to convert and cast the invoice_date and the getdate() function in that last line, but it gets an error attempting to convert the string to a date. What is the easiest way to accomplish this?
ASKER
I get the same result.
Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That was the problem. I knew that I had the castings right!
There were four fields that have been causing other problems because the user inputted tabs into the actual user form, which breaks the input for the tab-delimited file.
Thank you!
There were four fields that have been causing other problems because the user inputted tabs into the actual user form, which breaks the input for the tab-delimited file.
Thank you!
Try the following and see if that gives you what your are looking for.
Open in new window