SQL String in VBA in Excel 2010 with Dates - sql

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.

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.

converting date format in an access table with sql update

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.

VB.NET SQL date is changed format in query

I've got a date variable that looks like this:
Dim LogDate As Date = Date.Today.AddDays(-1)
the format comes out like: #4/5/2010#
then it goes into a SQL select query as a WHERE clause. When I debug, the query has changed this to '05/04/2010'. I want it to be in the format '04/05/2010' like it is when declared. Any ideas on how I do this?
Hee is the query:
Dim sqlCmd As New SqlCommand("SELECT TOP (100) PERCENT tblBackup.BackupName,
tblBackupArchive.BackupDate, tblStatus.Status FROM tblStatus INNER JOIN tblBackupArchive ON
tblStatus.StatusID = tblBackupArchive.StatusID INNER JOIN tblBackup ON tblBackupArchive.BackupID =
tblBackup.BackupID INNER JOIN tblClient ON tblBackup.ClientID = tblClient.ClientID WHERE tblBackupArchive.BackupDate = '" & LogDate & "' AND (tblBackupArchive.StatusID = 3) ORDER BY
tblBackupArchive.BackupDate DESC", connection)
-- Jonesy
The best way would be to use a SQLCommand object with a suitable named parameter in the where clause - this would make the formatting of the textual representation of the date totally beside the point...
Another approach, if you're using MS-SQL, would be to use a date in the following format:
Where date = '20100504'
Be careful when using dates though - remember that behind the scenes they are DateTimes...
Martin.