VBA - Convert string to datetime to compare with date in SQL - sql

Probably a simple question, but I haven't been able to find an answer on any forums yet.
I am using VBA to push data into SQL from an open source, and what I need my code to do is check the timestamp of the most recent data in SQL to determine if it needs to retrieve more data, or it is most up to date.
By using ADODB I can retrieve the latest date from SQL as follows
print latest_date
13/07/2021 8:14:50 PM
And the date from the data I want to collect as
print resource_date
'2021-07-13 20:14:50'
As you can see, the resource_date is a string, and the latest_date is an item from an ADODB recordset. These can't be compared in an If statement to see if they're the same.
I've tried using CDate() but I get mismatched type errors.
Any help is appreciated.
Thanks

Convert the text date to a true date value and use DateDiff to compare, for example by the second ("s"):
If DateDiff("s", print latest_date, CDate(resource_date)) > 0
' latest_date is earlier than resource_date.
End If

Related

character_length Teradata SQL Assistant

I have to run column checks for data consistency and the only thing that is throwing off my code is checking for character lengths for dates between certain parameters.
SEL
sum(case when ( A.date is null or (character_length(A.date) >8)) then 1 else 0 end ) as Date
from
table A
;
The date format of the column is YYYY-MM-DD, and the type is DA. When I run the script in SQL Assistant, I get an error 3580 "Illegal use of CHARACTERS, MCHARACTERS, or OCTET_LENGTH functions."
Preliminary research suggests that SQL Assistant has issues with the character_length function, but I don't know how to adjust the code to make it run.
with chareter length are you trying to get the memory used? Becuase if so that is constant for a date field. If you are trying to get the length of the string representation i think LENGTH(A.date) will suffice. Unfortanatly since teradata will pad zeros on conversions to string, I think this might always return 10.
UPDATE :
Okay so if you want a date in a special 'form' when you output it you need to select it properly. In teradata as with most DBs Date are not store in strings, but rather as ints, counting days from a given 'epoch' date for the database (for example the epoch might be 01/01/0000). Each date type in teradata has a format parameter, which places in the record header instructions on how to format the output on select. By default a date format is set to this DATE FROMAT 'MM/DD/YYYY' I believe. You can change that by casting.
Try SELECT cast(cast(A.date as DATE FORMAT 'MM-DD-YYYY') as CHAR(10)) FROM A. and see what happens. There should be no need to validate the form of the dates past a small sample to see if the format is correct. The second cast forces the database to perform the conversion and use the format header specified. Other wise what you might see is the database will pass the date in a date form to SQL Assitant and sql assitant will perform the conversion on the application level, using the format specified in its own setting rather then the one set in the database.

Update table Error Using Convert Function In SQL Server 2005

I have a table with two columns, all of them are datetime value
Such as, Column A with value ‘07/09/2012 14:13:34’
Now, I want to update column A to yyyymmdd by statement
Update Change_Date
SET A = CONVERT(VARCHAR(8),A,112)
It shows succsessful message but with no effect (no update value to 20120907) in my table Change_Date.
Any help will be greated, thank you!
A datetime fields saves a date time. How you see that date time is a result of the tool you're using to inspect the data, whether it is Management Studio, or your own software that's printing something from the database.
I strongly recommend keeping it as a datetime field. This will allow you to do date-related operations, such as subtractions and comparisons. If you want to change how your users see the date, then format your date at the presentation layer.
What's happening in the code you've posted is that you're setting the value of A to the same date that it already is. The fact that you're setting that value by means of a string in another format has no relation, SQL server will always have to parse your string input into a date that it can understand. This is why you're not getting an error message. The operation is working, only it's not changing anything.
You can select the date column in specified format or make a view which selects the column value in yyyymmdd format:
SELECT CONVERT(VARCHAR(8), A, 112) FROM Change_Date
It's because the datatype of the column is DATE or DATETIME and it has specific format. If you want to update the column with specific format, make another column and make its datatype VARCHAR. I believe 112 is yyyymmdd format.
I strongly suggest that you keep it AS IS. Database is the storage of data and not for viewing purposes. It is easy to perform task for dates if your data type is DATETIME or DATE. If for instance you want to retrieve the dates with specific format, that's the time you convert your date.
Hope this makes sense.

how to get excel to treat a date as a date not a string when doing CopyFromRecordset

I have an SQL query from SQL Server which returns dates as a string in the format "YYYY-MM-DD".
If I enter a date in this format into a cell, it's recognised as a date.
But when I populate a worksheet with CopyFromRecordset, it seems to be treated as a string.
Any formula which uses the cell converts it to a date first. For example, if my dates are in col A and I make a new column B filled with a formula =A1 + 0
the formula returns my date, as a date.
The problem:
I use the Recordset data for a few things, one of them being a pivot table.
The pivot table does not see my dates as dates. I can't group as dates, for example. My hack is to make a new column which is basically =A1 + 0
I'm going to change my macro to automate this adding a zero, but I wonder if there's a way to get it right from the moment the CopyFromRecordset is performed.
The easiest way would be to do the conversion on the SQL server e.g.
SELECT CAST(date_text AS DATE) FROM TestExcelDates;
CopyFromRecordset is well known for causing data type / cell formatting issues in Excel.
I think I remember reading somewhere this is because the datatype of the recordset is ignored and Excel attempts to work out the format of each column itself based on a subset of the data in the recordset.
The best way round this is to set the cell formatting in the destination range before performing the CopyFromRecordset.
I had this problem after I had changed a view on my SQL Server database. I had changed the data type to DATE; formerly it was on an older version which didn't support DATE so I had used DATETIME. I suspect Excel doesn't always recognize the Date datatype through the SQLOLEDB provider, but it does recognize DATETIME. The field of interest is meas_date. So I altered the view by changing this to a cast SELECT CAST(meas_date AS DATETIME) AS meas_date, ... and refreshed the query in Excel. Worked!
Use the CDate() function when populating cells with dates from the recordset. This will convert the string to a date value.
Edit
That works for setting individual cell values. For using CopyFromRecordset I think you need to do the conversino in the SQL query, so the column returned by the query is a date type rather than a string.
I had this problem too importing data from Teradata, and got around it by first formatting the date columns with NumberFormat = "m/d/yy h:mm;#" (24 hr date) then stepping through the date fields afterwards with VBA and doing ws.cells(iRow, iCol).value = ws.cells(iRow, iCol).value, it forces Excel to reevaluate the string into a date/time field.
This probably will not be the answer but will surely helps you finding the right solution for your problem
String stringCellValue = myCell.toString();
here myCell has datatype as CELL which I've converted to String format.
If u want it in desired Date format, then u can try this-
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
myCellDate = sdf.parse(stringCellValue );
Hope it helps in solving your problem...

MS Access - Select Char as Date and doing a date diff

I have two columns. ColA and ColB contains char(10) with data "20090520" and "20090521".
I want to select and get the date difference in days. I have tried using Format() and CDate()
but MS Access always display as #ERROR.
Access prefers its dates in this format:
#2009-12-01#
You can convert your date to something Access understands with:
CDate(Format([ColA], "0000-00-00"))
Or alternatively:
DateSerial(Left([ColA],4),Mid([ColA],5,2),Right([ColA],2))
And to display the result in your preferred format:
Format(<date here>, "dd-mm-yyyy")
Try using DateSerial() to convert the dates:
DateSerial(Left([FieldName],4),Mid([FieldName],5,2),Right([FieldName],2))
If at all possible, change the datatype to a date datatype. You should not store dates as character data.
I am connecting to another database which I have no control on. That is why this problem occurred. Thanks for the feedback.

How do I store just a date in MS SQL from VB?

My project requires I use VB (5 or 6)* to store a date in an SQL Server database. The SQL datetime type includes the time, which I don't want. I'm also aware that VB's representation of a date doesn't mirror that of SQL Server.
So, how can I store a date held in VB's date type in the SQL database, as the datetime at midnight on that date, for example?
Edit: I need to use the date to select rows further down the line, so I can't get away with just truncating it on read.
*I know, I you were me, you wouldn't start from here. But given the constraints, any VB6/MS SQL fiends out there?
VB6 has a DateValue() function which returns the date portion of a Date/Time value, with the time portion "zeroed out". (Note: When the time portion of a date/time variable is "zeroed out", the time would be interpreted as 12:00 AM.)
SQL Server 2008 has new date and time data types. There is the "Date" data type if you don't want to store the time component.
Use the DateTime column and just truncate the time at the presentation level.
Try inserting and updating the date like this:
CAST(FLOOR(CAST(#DateTime AS float)) AS datetime)
We have this in a UDF and it basically strips the time part from a datetime.
In VB you can use the Date() function to return the current date with no time element.
If you an use an ADO Parameter object with a Command object then the OLE DB provider should handle the conversion of a VB Date type to the SQL Server DATETIME value.
In SQL Server (pre SQL 2008 DATE type) you should create a CHECK constraint on the column to ensure it is not possible to add a date with a time element (note I've used an unambiguous language 'safe' format for my DATETIME literals) e.g.
ALTER TABLE MyTable ADD
vb_date DATETIME NOT NULL
CONSTRAINT vb_date__no_time_element
CHECK ((vb_date = DATEADD(DAY, DATEDIFF(DAY, '1990-01-01T00:00:00.000', vb_date), '1990-01-01T00:00:00.000')));
I would just use DateSerial to create the date you need. You pass it a year, month and day and it gives you a date with midnight as the time. You can then use it to pass as a parameter to an ADO command or similar. When you read it, it will have midnight so that isn't a problem. I like it better than DateValue as there is no string conversion. If you really want you can create your own function like DateValue that uses DateSerial.
Function JustTheDatePlease(ByVal dtSource As Date) As Date
JustTheDatePlease = DateSerial(Year(dtSource), Month(dtSource), Day(dtSource))
End Function
If for some reason you aren't using parameterized queries, and you really should have a good excuse for this, you can use the ODBC canonical form of a date in your queries. You just format the date as {d 'yyyy-mm-dd'} for example {d '2009-04-06'}.