Can you please help with implementation variable into SQL query in VBA? I am getting syntax error of date, timestamp or ODBC, DB2 ......thank you
Dim startdate As Date
Dim enddate As Date
startdate = InputBox(startdate, "YYYY-MM-DD")
enddate = InputBox(enddate, "YYYY-MM-DD")
I am trying to implement variable into where clause in the SQL statement:
where atindt>='" & startdate & "' and atindt<='" & enddate & "'
There is no reason to include startdate or enddate as arguments to InputBox
replace
startdate = InputBox(startdate, "YYYY-MM-DD")
enddate = InputBox(enddate, "YYYY-MM-DD")
by
startdate = InputBox("YYYY-MM-DD") 'perhaps with a more informative prompt
enddate = InputBox("YYYY-MM-DD")
and that part of the code will work as intended.
Related
I need help to filter between two dates and it's giving me an error:
Named argument not found
my code
Dim StartDate As String
Dim EndDate As String
'
StartDate = Date
EndDate = Date + 365
'
ActiveSheet.AutoFilter Field:=7, Criteria1:=">=StartDate", Operator:=xlAnd, Criteria2:="<=EndDate"
Any help would be much appreciated!
if your dates are actual Date values (i.e. not String ones looking like dates), then go like this:
Dim StartDate As Date
Dim EndDate As Date
StartDate = Date
EndDate = Date + 365
ActiveSheet.Range("A1:AO1").AutoFilter Field:=7, Criteria1:=">=" & CDbl(StartDate), Operator:=xlAnd, Criteria2:="<=" & CDbl(EndDate)
I posted a sample file on my google drive.
https://drive.google.com/open?id=0B2w6b7-P-pX1R0dlTlFUSl9xZlE
I can describe the logic, but it's just easier for you to download it, play around with it, and see the mechanics of it.
Basic logic was the issue... mix up of the start and end date logic (should be EndDate = Date and StartDate = Date - 365).
Sorry for the troubles!
I have a table in which data is been logged in 'yy/MM/dd HH:mm:ss' format and my regional setting is '2016-04-02 14:25:15' type. I want to get details in a following query but it is not populating any results
The query I used is
select
Date_time, alarm_id, alarm_message
from
table01
where
Date_time between '" & DateTimePicker5.Value & "' and '" & DateTimePicker6.Value & "'
I also tried using one function which I had written is
Private Function FormatDate(ByVal dat As String) As String
Dim FTDate As Date
FTDate = FormatDateTime(Convert.ToDateTime(dat), DateFormat.ShortDate)
FormatDate = Format(FTDate, "yy/MM/dd HH:mm:ss")
End Function
And used the same again in query as
select
Date_time, alarm_id, alarm_message
from
table01
where
Date_time between '" & formatdate(DateTimePicker5.Value) & "' and '" & formatdate(DateTimePicker6.Value) & "'
Please suggest appropriate answer make sure that I don't want to change my regional setting and on form load event. I've written the following code
DateTimePicker5.Format = DateTimePickerFormat.Custom
DateTimePicker5.CustomFormat = "yy/MM/dd HH:mm:ss"
DateTimePicker6.Format = DateTimePickerFormat.Custom
DateTimePicker6.CustomFormat = "yy/MM/dd HH:mm:ss"
The Table Is In Below Mentioned Format
**Datetime V1 P1**
16/08/29 19:12:24 10 STB-1
16/08/29 19:12:19 20 STB-1
16/08/29 19:12:18 30 STB-1
16/08/29 19:09:50 40 STB-1
Never ever ever EVER use string concatenation to put values into a query like that! It's practically begging to wake up one morning and find out your site was hacked six months ago.
The first thing you need to do is fix the schema, so that your date values are actually stored as DateTime columns. There are so many reasons for this, I can't even begin to describe them all. Just do it!
Once that's done, you build the query like this:
Const SQL As String = _
"SELECT Date_time, alarm_id, alarm_message
FROM table01
WHERE Date_time between #StartTime AND #EndTime"
Hey, look: it's a constant. Now that's not strictly necessary; I usually just use a normal Dim'd String value. However, I wanted to prove a point here: your SQL statement is set to use specific place holders that will never at any point have data in them. The values you provide for those #StartTime and #EndTime values will be completely separated and quarantined from your SQL command, such that no possibility for injection ever exists.
Once you have the SQL command string, you can use it like this (repeating the string definition so everything is in one place):
Const SQL As String = _
"SELECT Date_time, alarm_id, alarm_message
FROM table01
WHERE Date_time between #StartTime AND #EndTime"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(SQL, cn)
cmd.Parameters.Add("#StartTime", SqlDbType.DateTime).Value = DateTimePicker5.Value
cmd.Parameters.Add("#EndTime", SqlDbType.DateTime).Value = DateTimePicker6.Value
cn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
' ...
End While
End Using
End Using
Or if you're filling a DataTable:
Dim result As New DataTable()
Const SQL As String = _
"SELECT Date_time, alarm_id, alarm_message
FROM table01
WHERE Date_time between #StartTime AND #EndTime"
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(SQL, cn), _
ad As New SqlDataAdapter(cmd)
cmd.Parameters.Add("#StartTime", SqlDbType.DateTime).Value = DateTimePicker5.Value
cmd.Parameters.Add("#EndTime", SqlDbType.DateTime).Value = DateTimePicker6.Value
ad.Fill(result)
End Using
Note that using this method, you never have to worry about your DateTime format. ADO.Net figures it out for you. It knows about .Net DateTime objects, and it knows about Sql Server DateTime columns, and it handles conversions between the two types naturally.
This is some what a tricky solution.
Since year kept as 'yy' in the backend,following are the assumptions.
if the year part of the database field is between 00 to 16 ,need to consider this as 2000 to 2016. for the remaining values script will consider year as 1917 to 1999 .
Can you try with the below script.
SELECT Date_time, alarm_id, alarm_message
FROM table01
WHERE
CASE WHEN LEFT(Date_time,2) between 00 and RIGHT(year(getdate()),2) THEN CONVERT(DATETIME,'20'+Date_time)
ELSE CONVERT(DATETIME,'19'+Date_time) END between '" & DateTimePicker5.Value & "' and '" & DateTimePicker6.Value & "'
You can use Convert function.
select
Date_time, alarm_id, alarm_message
from
table01
where
Convert(Datetime,Date_time) between Convert(Datetime,'" & DateTimePicker5.Value & "') and Convert(Datetime,'" & DateTimePicker6.Value & "')
Since:
Console.WriteLine(#1/31/2016 10:23:22 AM#.ToString("yy/MM/dd HH:mm:ss"))
returns 16/01/31 10:23:22
I guess that:
select
Date_time, alarm_id, alarm_message
from
table01
where
(Date_time >= '" & DateTimePicker5.Value.ToString("yy/MM/dd HH:mm:ss") & "' )
and (Date_time < '" & DateTimePicker6.Value.ToString("yy/MM/dd HH:mm:ss") & "')
will do the trick.
Notice that I've changed the between with simple compare conditions
Run this in SQL Server and check the results:
create table #dateTest (
testDate datetime
)
insert into #dateTest values ('2016-03-01')
select * from #dateTest
declare #fromDate datetime
set #fromDate = '2016-01-01'
declare #toDate datetime
set #toDate = '2016-03-01'
select
testDate
from
#dateTest
where
( testDate between #fromDate and #toDate )
-- 2016-03-01 00:00:00.000
select
testDate
from
#dateTest
where
( testDate <= #fromDate )
and ( testDate < #toDate )
-- No rows selected
drop table #dateTest
I have this code in VBA:
FilterString = "CalanderDate<#" & EndOfWeek(InDate) & "# AND CalanderDate >#" & StartOfWeek(InDate) & "#"
Me.Filter = FilterString
Me.FilterOn = True
The code for EndOfWeek and StartOfWeek is as follow:
Function StartOfWeek(InDate As Date) As Date
inWeekday = Weekday(InDate, vbMonday)
StartOfWeek = InDate - inWeekday + 1
End Function
Function EndOfWeek(InDate As Date) As Date
EndOfWeek = StartOfWeek(InDate) + 7
End Function
The idea is to filter the data based on dates which fall in a specific week ( in the same week and inDate)
But when I run this, I am getting strange behaviour:
If InDate is 2/6/2014, then I have records with the following dates:
12/05/2014
21/05/2014
22/05/2014
23/05/2014
which none of them fell into the week of 2/6/2014 to 9/6/2014
If I set the inDate to 20/05/2014, I am getting the following records:
21/05/2014
22/05/2014
23/05/2014
Why the filtering doesn't work properly and how can I fix it?
Edit1
Deleted as it was wrong. Andy answer is correct.
CalanderDate<#" & EndOfWeek(InDate) & "# AND CalanderDate >#" & StartOfWeek(InDate) & "#"
Access is fussy about the date format and, in particular, reverts to the US format mm/dd/yyyy.
In the above expression use Format() with either:
Format(EndOfWeek(InDate),"mm/dd/yyyy")
or
Format(EndOfWeek(InDate),"yyyy-mm-dd")
and the same for StartOfWeek.
Please help me how to insert LIKE % in date between. Example is:
SELECT *
FROM table
WHERE Date BETWEEN '" & startDate & "%'" AND '" & endDate & "%'"
So in this code where i should put LIKE so that data will appear?
example if i set like this
SELECT *
FROM table
WHERE Date LIKE '" & startDate & "%'"
it's working..LIKE meant read either startdate or %..for starting it will read %
Try this :
"Select (listOfFields)
FROM TABLE
where CONVERT(VARCHAR(25), Your_DATE, 126) BETWEEN 'Start_date%' AND 'EndDate%'";
Try something like this
SELECT * from table
WHERE CONVERT(VARCHAR, DateField, 120) BETWEEN '2010%' AND '2012%'
If the dates are of type string, you can't use BETWEEN*.
If the dates are of type date or datetime, you can't use LIKE.
*Actually between might work with text because b is between a and c but it will not return correct results with date strings.
I get this error when I run the application Incorrect syntax near 12, on debugging I found that this error is caused due to the # along with the date.
Dim backdate as datetime
backdate = DateTime.Now.AddDays(-1)
on binding the data to the grid to filter the backdate records this error is caused Incorrect syntax near 12.
myqry = " select SRNO,SUBJECT,ID where datesend =" backdate
Now i am trying to extract only the date or shall I divide the date into day , month and year with DATEPART and take into a variable or convert the date or what should i do , Please help ???
This is the correct statement:
myqry = "select SRNO,SUBJECT,ID where cast(convert(char(10), datesend, 121) as datetime) ='" & backdate.ToString("yyyy-MM-dd") & "'"
Cast and Convert: http://msdn.microsoft.com/en-us/library/ms187928.aspx
Convert with parameter 121 will convert to the following format: yyyy-mm-dd hh:mi:ss.mmm(24h), from that string, we get the first 10 characters (char(10)).
Without parameters:
myqry = "Select SRNO,SUBJECT,ID From ... Where convert(char(10), datesend, 121) = convert(char(10), dateadd(day,-1,getdate()), 121)"
Note that you are missing the ampersand (&) in your query. Also, try putting your date in quotes in the query:
myqry = " select SRNO,SUBJECT,ID where datesend ='" & backdate.ToString('yyyy-MM-dd') & "'"
myqry = " select SRNO,SUBJECT,ID where datesend = '" & backdate.tostring("dd MMMM yyyy") & "'"