converting date format in an access table with sql update - sql

I have a problem converting dates while updating an SQL table in VB under access: here is my code:
'Excel format date conversion
strSQL = "UPDATE tblBlotterINTLControl " & _
"SET tblBlotterINTLControl.TradeDate = CVDate(TradeDate), " & _
"tblBlotterINTLControl.SettleDate = CVDate(SettleDate);"
DoCmd.RunSQL strSQL
I obtain an error for each row: "type conversion error"
I have my tables in the right format though, please help thanks
EDIT:
I have to say that a SELECT request works but an UPDATE request doesn't! why? how?

What are the data types of the TradeDate and SettleDate fields in the Access table tblBlotterINTLControl?
SELECT TypeName(TradeDate) AS TypeOfTradeDate, TypeName(SettleDate) AS TypeOfSettleDate
FROM tblBlotterINTLControl;
Please paste that query into SQL View of a new query in Access, run it and show us what you get back.
The reason I asked is because the SET statements in your UPDATE query puzzle me.
SET tblBlotterINTLControl.TradeDate = CVDate(TradeDate)
If the TradeDate field is Date/Time datatype, using the CVDate() function on it doesn't accomplish anything.
If the TradeDate field is text datatype, CVDate() will give you a variant date, but you can't store that Date/Time value back to your text field.
Maybe you would be better off using the Format() function. Here is a sample I copied from the Immediate Window:
? Format("2011/01/01", "d mmm yyyy")
1 Jan 2011

Try CDate instead of CVDate.
CVDate actually returns a Variant of type vbDate and is only around for backwards comparability. Maybe that's what causing the problems.

Related

SQL: Compare Date Range in a String text field

I have an MS Access db. I am writing an application in C# to access it. I have a field "FileName" of type "Short Text in MS Access. Data in FileName field is like "Test 11-12-2004 15.11.15".
Using a Date Range, I got to search records based on FileName field. I am not able to get - How do I compare the date of this format and retrieve the records ? FileName is a Text type and date is a substring of it. Retrieving only the date part and comparing with >= beginDate && <= endDate seems like a puzzle to me.
Can anyone suggest how do I write SQL query to perform this date range comparision and retrieve those records - "Select * from TestHead where FileName......" ????
Any help is appreciated.
Thanks a lot,
In your C# code, as you are going through the records, I'd split the string like this:
char[] delimiters = {' '};
string[] FileNameParts = FileName.Split(delimiters);
This will result in an array FileNameParts, the second element of which will contain the date, which you can convert to an actual date for use in the query:
DateTime FileNameDate = Convert.ToDateTime(FileNameParts(1))
Something along the lines of:
sSQL = "SELECT * FROM Table WHERE " & beginDate & " <= " & FileNameDate
I see this as preferable to adding a column to your table that contains the date substring of the FileName field, because then you constantly need to be updating that column whenever existing records are modified or new records are added. That means more clutter on the C# side, or an UPDATE query on the Access side which at least needs to get called periodically. Either way it would be more communication with the database.

Access 2003 - VBA - Joining on two types (string = date)

Background: Im busy with a research, in which I receive data stored in a oracle database. I myself use an Access database to store the data from the oracle database (and as well data from other sources, not relevant for this question)
The data from the oracle database is given to me in access format. Then I run the following query to retrieve the "oracle data" and insert (or update if the row already excist) into my own access database.
The oracle database export saved it's dates in text format, I have date formats in my own database, so I use a VBA function to transform the texts in dates.
My question: Can I join on a string and a date if the string is transformed to a date? How should I proceed?
UPDATE [TABLE1] INNER JOIN [URI_to_oracle_export.mdb].[TABLE2]
ON ([TABLE1].PT=[TABLE2].PT)
AND ([TABLE1].DCMDATE=toDateFunction([TABLE2].DCMDATE))
AND ([TABLE1].CPEVENT=[TABLE2].CPEVENT) SET ...the rest of the SQL..
My toDateFunction:
Function toDateFunction(input As String)
toDateFunction= CDate(Right(input , 2) & "/" & Mid(input , 5, 2) & "/" & Left(input , 4))
End Function
So based on your conversion function it looks as though the Oracle text format you are receiving is YYYYMMDD, for using type conversions for a join in this case I would prefer to work the other way round and transform my access value to text e.g:
WHERE OracleTable.Date = Format(AccessTable.Date, "YYYYMMDD")
Or
INNER JOIN OracleTable ON OracleTable.Date = Format(AccessTable.Date, "YYYYMMDD")
You could still do it in reverse and convert your Oracle value to a date if you wanted which would be more like:
WHERE DateSerial(Left(OT.Date,4),Mid(OT.Date,5,2),Right(OT.Date,2)) = AT.Date
When building your date value literally I prefer using DateSerial to CDate

Date Subtraction within Select Statement

I am currently working on an MS Access database, and am having problem with date subtraction.
Essentially I am trying to create a target date for example:
Target Date = Deadline - Lead Time
i.e. the lead time could be 30 days, therefore the target date should be 30 days prior to the deadline.
The code I am trying to use is this:
strSQL = "INSERT INTO dbo_DEALER_TASK ( Dlr_Number, Action_Id, Task_Id, Area_Id,
Task_Deadline_Date, Responsible_Person_Id, Alternate_Person_Id, Priority, Comment,
Suppress_Email, Dealer_Type ) "
strSQL = strSQL & "SELECT dbo_DEALER_ACTION.Dlr_Number, dbo_DEALER_ACTION.Action_Id,
qryAllTasksToAdd.Task_Id, qryAllTasksToAdd.Area_Id, Deadline_Date - Deadline_adjustment
AS 'Task_Deadline_Date', qryAllTasksToAdd.Person_Responsible_Id,
qryAllTasksToAdd.Alternate_Responsible_Id, qryAllTasksToAdd.Priority,
qryAllTasksToAdd.Comment, qryAllTasksToAdd.Suppress_Email,
qryAllTasksToAdd.Applies_To_Dealer_Type "
strSQL = strSQL & "FROM dbo_DEALER_ACTION LEFT JOIN qryAllTasksToAdd ON
(dbo_DEALER_ACTION.Dealer_Type = qryAllTasksToAdd.Applies_To_Dealer_Type) AND
(dbo_DEALER_ACTION.Action_Id = qryAllTasksToAdd.Action_Id) "
strSQL = strSQL & WHERE (((qryAllTasksToAdd.Task_Id)=" & Me.Task_Id & ") AND
((dbo_DEALER_ACTION.Date_Completed) Is Null));"
DoCmd.RunSQL strSQL
When the VBA code executes the statement, everything is updated correctly, except for the Task_Deadline_Date field, which is being left blank.
What is really confusing me though is if I run this SQL statement standalone it is working as expected. After trying a number of different ideas I tried to replace "Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'" with a string literal date and the statement then worked fine
Does anybody have any ideas what is going wrong?
Thanks,
Chris
You have quoted the alias, you should not do that:
Deadline_Date - Deadline_adjustment AS Task_Deadline_Date
Not
Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'
When you add the quotes, the name of the field is 'Task_Deadline_Date'
Depending on the data type of your date field and whether or not you are using SQL Server, you may need to use DateAdd, for example:
DateAdd("d",-[Deadline_adjustment],[Deadline_Date])
In Access' query designer, start with the version of your query which works and convert it to a parameter query.
WHERE
qryAllTasksToAdd.Task_Id=[which_id]
AND dbo_DEALER_ACTION.Date_Completed Is Null;
You can also add a PARAMETERS statement at the start of the query to inform the db engine about the data type of your parameter. Examples ...
PARAMETERS which_id Text ( 255 );
PARAMETERS which_id Long;
Once you get that query working, save it and give it a name. Then your VBA procedure can use that saved query, feed it the parameter value, and execute it.
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.QueryDefs("YourQuery")
qdf.Parameters("which_id").value = Me.Task_Id
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
This should be much easier than trying to recreate that SQL statement in VBA code each time you need to execute it.
It sounds like the data type of the column you are inserting in dbo_DEALER_TASK is not actually a datetime field.
I tried to replace "Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'" with a string literal date and the statement then worked fine
If you mean '02/20/2012' (as you would correctly use on SQL Server, for example) then this shouldn't work in Access and only will if your output column is a text (= varchar/char)) data type. Date constants in Access are specified like #02/20/2012#
Please confirm the data type of Task_Deadline_Date in your output table.

SQL String in VBA in Excel 2010 with Dates

I've had a look around but cannot find the issue with this SQL Statement:
strSQL = "SELECT Directory.DisplayName, Department.DisplayName, Call.CallDate, Call.Extension, Call.Duration, Call.CallType, Call.SubType FROM (((Department INNER JOIN Directory ON Department.DepartmentID = Directory.DepartmentID) INNER JOIN Extension ON (Department.DepartmentID = Extension.DepartmentID) AND (Directory.ExtensionID = Extension.ExtensionID)) INNER JOIN Site ON Extension.SiteCode = Site.SiteCode) INNER JOIN Call ON Directory.DirectoryID = Call.DirectoryID WHERE (Call.CallDate)>=27/11/2012"
Regardless of what I change the WHERE it always returns every single value in the database (atleast I assume it does since excel completely hangs when I attempt this) this SQL statement works perfectly fine in Access (if dates have # # around them). Any idea how to fix this, currently trying to create a SQL statement that allows user input on different dates, but have to get over the this random hurdle first.
EDIT: The date field in the SQL Database is a DD/MM/YY HH:MM:SS format, and this query is done in VBA - EXCEL 2010.
Also to avoid confusion have removed TOP 10 from the statement, that was to stop excel from retrieving every single row in the database.
Current Reference I have activated is: MicrosoftX Data Objects 2.8 Library
Database is a MSSQL, using the connection string:
Provider=SQLOLEDB;Server=#######;Database=#######;User ID=########;Password=########;
WHERE (Call.CallDate) >= #27/11/2012#
Surround the date variable with #.
EDIT: Please make date string unambiguous, such as 27-Nov-2012
strSQL = "SELECT ........ WHERE myDate >= #" & Format(dateVar, "dd-mmm-yyyy") & "# "
If you are using ado, you should look at Paramaters instead of using dynamic query.
EDIT2: Thanks to #ElectricLlama for pointing out that it is SQL Server, not MS-Access
strSQL = "SELECT ........ WHERE myDate >= '" & Format(dateVar, "mm/dd/yyyy") & "' "
Please verify that the field Call.CallDate is of datatype DATETIME or DATE
If you are indeed running this against SQL Server, try this syntax for starters:
SELECT Directory.DisplayName, Department.DisplayName, Call.CallDate,
Call.Extension, Call.Duration, Call.CallType, Call.SubType
FROM (((Department INNER JOIN Directory
ON Department.DepartmentID = Directory.DepartmentID)
INNER JOIN Extension ON (Department.DepartmentID = Extension.DepartmentID)
AND (Directory.ExtensionID = Extension.ExtensionID))
INNER JOIN Site ON Extension.SiteCode = Site.SiteCode)
INNER JOIN Call ON Directory.DirectoryID = Call.DirectoryID
WHERE (Call.CallDate)>= '2012-11-27'
The date format you see is simply whatever format your client tool decides to show it in. Dates are not stored in any format, they are effectively stored as a duration since x.
By default SQL Uses the format YYYY-MM-DD if you want to use a date literal.
But you are much better off defining a parameter of type date in your code and keeping your date a data type 'date' for as long as possible. This may include only allowing them to enter the date using a calendar control to stop ambiguities.

Dealing with dates in dd/mm/yyyy format

I have a VB6 application which works with datetime values in SQL Server (which are obviously storing dates as mm/dd/yyyy).
I need to represent these dates to the user as dd/mm/yyyy, read them in as dd/mm/yyyy, and then store them back into the database as the standard mm/dd/yyyy.
This is the current code snippets I have which pull + insert the dates, however I have read many conflicting methods of handling the conversions, and I was wondering if anyone here knew a clear solution for this situation.
"SELECT * FROM List WHERE DateIn LIKE '%" & txtDateIn.Text & "%'"
"UPDATE [Progress] SET [Date] = '" & txtDate.Text & "'"
txtDate.Text = "" & RecordSet.Fields("Date").Value
Any thoughts? Thanks in advance.
**Update
Actually I just noticed I do have dates stored in datetime fields in the form of 16/08/2009 00:00:00 which is dd/mm/yyyy. So perhaps I misunderstood the problem. But when trying to update the datetime value I have been getting 'The conversion of char data type to a datetime data type resulted in an out-of-range datetime value.'.
I assumed this was because the date formats did not match (causing a problem with having a month value out of range) however I do have date values in the format of day/month/year in the datetime field already. And the date being submitted to the database is definitely dd/mm/yyyy.
**** Update 2**
Ok, there seems to be some confusion I have caused. I apologize.
I am storing the dates as datetime in the SQL database
The texts are TextBox controls in the VB6 application
I am running SQL SELECT statements to read the dates from the database and place the value in a TextBox
I then have a 'commit' command button which then performs an UPDATE SQL statement to place the value of the TextBox into the datetime field in the SQL database
This works perfectly fine until 1 specific occasion.
In this occasion I have a datetime value (which SQL Server 2005 displays as 16/08/2009 00:00:00) which is read from the database and populated the TextBox with the value 16/08/2009. Now when I try to run the UPDATE statement without modifying the TextBox text I get the error 'The conversion of char data type to a datetime data type resulted in an out-of-range datetime value.'
This does not occur with other records such as one where the date is 04/08/2009 so the only issue I can see is possibly with the position of day and month in the value because if the DB is expecting month first then obviously 16/08/2009 would be out-of-range. However the value in the database is already 16/08/2009 with no issues.
SQL Server doesn't "obviously" store dates as mm/dd/yyyy. It doesn't store them in a text format at all, as far as I'm aware.
I don't know what the VB6 support for parameterised queries is, but that's what you want: basically you want to pass the argument to the query as a date rather than as text. Basically you should parse the user input into a date (in whatever way VB6 does this) and then pass it through in the paramterised query.
EDIT: I've tried to find out how VB6 handles parameterised queries, and not had a great deal of luck - hopefully any good book on VB6 will cover it. (There are loads of examples for VB.NET, of course...) There's a Wrox post which gives an example; that may be enough to get you going.
EDIT: As the comment to this answer and the edit to this question edit indicate, there's some confusion as to what your data types really are. Please don't use character-based fields to store dates: no good can come of that. Use a proper date/datetime/whatever field, and then make sure you use parameterised queries to access the database so that the driver can do any necessary conversions. Relying on a text format at all is a bad idea.
Use the ODBC Canonical form of the date or timestamp in your queries.
This avoids any misunderstanding due to localization when storing the dates.
The timestamp format is {ts 'yyyy-mm-dd hh:mm:ss[.fff]'}
The date format is {d 'yyyy-mm-dd'}
Here are the functions I use for this.
Now as for entry and display in VB6. Ideally you'd be using the datetimepicker control instead of a textbox as that returns a date and there is no misunderstanding when using it which date you are picking. But if you can assume it is always DD/MM/YYYY (that is a big if), you can use Format(datevalue, "DD/MM/YYYY") to display it. To read it into a date variable you can't just use CDate. You'll need to use parsing and something like DateSerial to put it together: DateSerial(Right(strDate, 4), Mid(strDate, 4, 2), Mid(strDate, 1, 2)).
' ------------------------------------------------------------------------------
' DateLiteral
'
' Description :
' given a vb date, it returns a string with the odbc canonical date format.
'
' History
' 2008-02-04 - WSR : added to this project
'
Public Function DateLiteral(ByRef dtSource As Date) As String
DateLiteral = _
"{d '" & LeftPadDigits(Year(dtSource), 4) & "-" & _
LeftPadDigits(Month(dtSource), 2) & "-" & _
LeftPadDigits(Day(dtSource), 2) & "'}"
End Function
' ------------------------------------------------------------------------------
' ------------------------------------------------------------------------------
' TimeStampLiteral
'
' Description :
' given a vb date, it returns a string with the odbc canonical timestamp format.
'
' History
' 2008-02-04 - WSR : added to this project
'
Public Function TimeStampLiteral(ByRef dtSource As Date) As String
TimeStampLiteral = _
"{ts '" & LeftPadDigits(Year(dtSource), 4) & "-" & _
LeftPadDigits(Month(dtSource), 2) & "-" & _
LeftPadDigits(Day(dtSource), 2) & " " & _
LeftPadDigits(Hour(dtSource), 2) & ":" & _
LeftPadDigits(Minute(dtSource), 2) & ":" & _
LeftPadDigits(Second(dtSource), 2) & "'}"
End Function
' ------------------------------------------------------------------------------
' ------------------------------------------------------------------------------
' LeftPadDigits
'
' Description : pads the given string to the left with zeroes if it is under
' the given length so that it is at least as long as the given length.
'
' History
' 2008-02-04 - WSR : added to this project
'
Public Function LeftPadDigits(ByVal strSource As String, ByVal lngLength As Long) As String
If Len(strSource) < lngLength Then
LeftPadDigits = String$(lngLength - Len(strSource), "0") & strSource
Else
LeftPadDigits = strSource
End If
End Function
' ------------------------------------------------------------------------------
Also should be noted, yes the first choice is to use ADO and parameterized queries.
In my case I access the database through a third party library and can't use parameterized queries. Thus the date literal handling. Here is an example of the ADO parameterized queries though. The code can be different depending on which type of ADO connection you are using though: OLEDB, ODBC or SQLNative. Sometimes it isn't just a ? for the parameter marker. This example is OLEDB.
Set cmdVerifyUser = New ADODB.Command
cmdVerifyUser.CommandType = adCmdText
cmdVerifyUser.CommandTimeout = 30
cmdVerifyUser.CommandText = "SELECT username FROM users WHERE userid = ?"
cmdVerifyUser.Parameters.Append cmdVerifyUser.CreateParameter("userid", adVarChar, adParamInput, Len(m_strUserName), m_strUserName)
cmdVerifyUser.ActiveConnection = m_conDatabase
Set rstResults = cmdVerifyUser.Execute()
If Not rstResults.EOF Then
Well after all of that the problem was simple. I have the date value wrapped in single (') and double (") quotes. The problem was encountered due to date values not requiring the single quotes. Removing them solved the issue.
Thank you anyway for trying to help all.