Automatically delete rows with Sunday Date - vb.net

Hello guyz please help.
From snapshot above the "Date" column has sunday date "3/17/2017" and "3/26/2017". I want to delete row with Sunday in the column of "Date" automatically when I imported an attendance log to the datagridview.
so far my code is just to delete one by one:
conn.Open()
cmd.Connection = conn
cmd.CommandText = "DELETE FROM tblEmployeeAttendance WHERE [Date] = '3/17/2017' "
cmd.ExecuteNonQuery()
conn.Close()
but I want to delete upon load to the datagridview.

Try this to change date
While fromatafter.DayOfWeek = DayOfWeek.Saturday OrElse fromatafter.DayOfWeek = DayOfWeek.Sunday
fromatafter = fromatafter.AddDays(-1)
End While
dates.Add(fromatafter.ToString("MM/dd/yyyy"))
You need to assigne the date returned from dates to your variable.

You can use datepart function for sql command
DELETE FROM tblEmployeeAttendance WHERE Datepart(dw,[Date])=1

Related

Filter between dates VB.NET and Access database

As the title says, I'm unable to filter an SQL sentence from access database with vb.net
Dim data1 As String = DateTimePicker1.Value.ToShortDateString
Dim data2 As String = DateTimePicker2.Value.ToShortDateString
Dim sql As String = "SELECT totais.* From totais Where totais.data Between #" + data1 + "# And #" + data2 + "#;"
It gives me random values. If i put 1-10(October)-2019 it gives me all the records in system, if i put 12-10(October)-2019 it only gives today's record (doesn't show yesterday and before records). I'm not finding the problem, can you please help?
Thanks
I would use Parameters instead of concatenating a string for the Sql statement. It makes the statement much easier to read and avoids syntax errors.
With OleDb the order that parameters appear in the sql statement must match the order they are added to the parameters collection because OleDb pays no attention to the name of the parameter.
Private Sub OPCode()
Dim sql As String = "SELECT * From totais Where data Between #StartDate And #EndDate;"
Using dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand(sql, cn)
cmd.Parameters.Add("#StartDate", OleDbType.Date).Value = DateTimePicker1.Value
cmd.Parameters.Add("#EndDate", OleDbType.Date).Value = DateTimePicker2.Value
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
DataGridView1.DataSource = dt
End Using
End Sub
You need to use single quotes and convert type in SQL like this:
SELECT totais.* FROM totais WHERE totais.data Between CDATE('" + data1 + "') And CDATE('" + data2 + "');"
You should use parameters as per Mary's answer BUT for completeness...
Ms/Access requires dates specified as #mm/dd/yy# so your SQL will only work properly where the local date time format is mm/dd/yy. i.e. mostly the US. Otherwise you will have to format your date string.

SQL Selecting without parameters?

Im trying to select all records from a database table. Each record has a date in it i want to select all records where that date matches todays date
i created a variable called todaydate and used it within the query but i get No value provided for one or more required parameters error. What possible parameters would i use
Here is the code
Any help would be appreciated
Dim todaydate As Date = Date.Today()
If DbConnect() Then
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * from Tbl_Rental Where DateOfHire = todaydate"
'parameters????
You're not using the variable. However, you should always use sql-parameters not concatenate strings(one reason: avoiding SQL-Injection). I'd also suggest to use the Using-statement for the connection and everything else that implements IDisposable:
Using cn As New OleDbConnection(connectionString)
cn.Open()
Using cmd As New OleDbCommand("Select * from Tbl_Rental Where DateOfHire = #DateOfHire", cn)
dim hireDateParameter As new OleDbParameter("#DateOfHire", OleDbType.Date)
hireDateParameter.Value = Date.Today
cmd.Parameters.Add(hireDateParameter)
' ... '
End Using
End Using
If it's always Date.Today you could do that also without a parameter because every database has date functions which return the current date. But since you haven't told us which DB you are using it's hard to show an example.
You need to actually use your variable, not include it as part of the string. Try this:
.CommandText = "Select * from Tbl_Rental Where DateOfHire = '" & todaydate.ToString("dd/MM/yy") & "'"
From a slightly different angle, would it suffice that the date was simply "greater than yesterday"?
.CommandText = "Select * from Tbl_Rental Where DateOfHire >= cast(getdate() as date)"
This strips the time off the date and anything at or later than midnight today is included.

How to Condition the two Date and time from database into label current date and time

How to compare the date from MS Access Column "Time" in Time in my label form.
heres my code
Dim sql = "Select CompanyCode From LAPostingCoCode where CompanyCode = '" + ComboBox1.text"' AND User = '" & txtuser.text & "' AND Time = '" & LblTime.text & "'"
Using Olecon As New OleDbConnection(cons)
Using command as new OleDbDCommand(sql,olecon)
Using adapter as New OleDbDataAdapter(command)
Dim Table As New DataTable()
adapter.Fill(table)
If (table.Rows.Count > 0 ) Then
btnSave.Enabled = false
Else
btnSave.Enabled = true
End If
End Using
End Using
End using
I want to compare the date and time from database Column into my Form Label Current Date and Time. So that if the date and time in the database is 02-02-18 4:42:01, and in my label is 02-02-18 05:02:31. the button save will be enabled = true because the time is almost 5pm. when 4:42:01 is equal into time label. the save button still enabled = false.
I am using vb.net and MS access. help me please. thanks
The code will let you compare two dates , please modify the code as required :
'Assuming your date is formatted as : dd/mm/yyyy
Dim date1 = DateTime.Parse("02/05/2018")
Dim date2 = DateTime.Parse("03/07/2018")
If date1.Date >date2.Date Then
End if
Now for example , for example , you want to compare dateTime column of your table with your label's date(i mean .text),do this "
Dim dt1 = DateTime.Parse(yourDataTable(0)(3)) 'Here 0 is the row count and 3 is the column count
'Follow the first code block's code now :)
Suggestion: Please don't use direct values in your Select statement as it opens doors to Sql-Injection.
Read more about SQL-Injection
Rather,pass parameters and use your SqlCommand to pass values :
Dim cmd as new SqlCommand("Select CompanyCode From LAPostingCoCode where CompanyCode = #code",connection)
cmd.Parameters.Add("#code",SqlDbType.VarChar).Value = ComboBox1.text
And please use Parameter.Add method , most people use AddWithValue which not the proper way.Because at points, it may not cause errors/may not conflict with data but in most cases it'll corrupt the data.The reason is that , it infers the database type to query parameter.
Read more here
Hope this helps :)

DB2 SQL Query to group by week

I am writing an ASP.NET web form page using VB.Net. I am writing code to use on a line graph, but I can't seem to get my query to group by week. Here is my query:
SELECT F42119LA.SDMCU || '-' || F42119LA.SDLNTY AS BranchCode,
AVG(F42119la.SDIVD-F42119LA.SDDRQJ) AS Days,
WEEK(SDTRDJ) AS Day
FROM KAI400.KAIPRDDTA.EXCHBYDATE EXCHBYDATE,
KAI400.KAIPRDDTA.F42119L14 F42119LA
WHERE F42119LA.SDBCRC = EXCHBYDATE.CXCRCD
AND EXCHBYDATE.EXCHDATE = F42119LA.SDTRDJ
AND F42119LA.SDTRDJ>='118006'
AND F42119LA.SDTRDJ<='118096'
AND F42119LA.SDNXTR<>'999'
AND SDIVD <> 0
AND SDDRQJ <> 0
AND F42119LA.SDAEXP <> 0
AND EXCHBYDATE.CXCRDC='USD'
AND F42119LA.SDLNTY IN ('S','W')
AND (SDMCU LIKE '%100' OR SDMCU LIKE '%150')
GROUP BY SDMCU,
SDLNTY,
SDIVD,
F42119LA.SDMCU || '-' || F42119LA.SDLNTY,
WEEK(SDTRDJ)
ORDER BY SDIVD,
SDMCU,
SDLNTY
and this is the code the sql string runs through:
Public Shared Function GetMyDataTableString(SqlString As String, Optional IncDb As Integer = 0) As DataTable
Dim MyConn As OleDbConnection = GetMyConn(IncDb)
Dim DbCmd As New OleDbCommand(SqlString, MyConn)
Dim ReturnDataTable As New DataTable
Try
If Not MyConn.State = ConnectionState.Open Then
MyConn.Open()
End If
Dim Reader As OleDbDataReader = DbCmd.ExecuteReader(CommandBehavior.CloseConnection)
Using Reader
ReturnDataTable.Load(Reader)
End Using
Catch ex As Exception
LogSqlErrors(SqlString, "GetMyDataTableString " & ex.Message.ToString(), IncDb)
If HttpContext.Current.Session("SITEADMIN") = "True" Then
HttpContext.Current.Response.Write("<b>OleFun.GetMyDataTableString, datatable failed</b>---<br />" & ex.ToString)
End If
Finally 'Happens regardless of failing or succeeding
MyConn.Close()
End Try
Return ReturnDataTable
End Function
Whenever I use WEEK(), it gives me this error:
Value in date, time, or timestamp string not valid
ONDATE is a date field in format MM/DD/YYYY. Does anyone know another way to group by week or what might can be giving me this error? Thanks in advance for your responses.
-- date part takes the part of the date as first paramater:
-- you have:
DATEPART(SDTRDJ, wk)
-- needs to be:
DATEPART(wk, SDTRDJ)
DATEPART() might be a function in SQL Server, but it not a function in Db2. You could use WEEK() or WEEK_ISO() which are Db2 functions. https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0005481.html
You could also use EXTRACT if you are on a recent version of Db2 LUW
https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0053629.html
db2 "values extract(WEEK FROM current date)"
1
-----------
14
1 record(s) selected.
BTW you don't need to group by the concatenation of F42119LA.SDMCU || '-' || F42119LA.SDLNTY, you can group by those columns individually, and only concat in the SELECT.
In DB2, you can group days in same week using following methods:
DATE_PART('WEEK', dateColumn) -> week starts at Saturday
WEEK(dateColumn) -> week starts at Sunday
WEEK_ISO(dateColumn) -> week starts at Monday
DAYS(dateColumn) / 7 -> week starts at Sunday
Notes:
I believe that they work with columns of type DATE as will as TIMESTAMP.
"DAYS(dateColumn) / 7" doesn't get you week number, however it is helpful in grouping by week.
Kindly check your week start day as they differ in their results as following:

Datagridview SQL returning no results

Upon loading the form, this code is carried out:
Try
MyConn2.Open()
da2 = New OleDbDataAdapter("Select * from tbl_bookings WHERE DateOfBooking = " & DateTime.Today, MyConn2)
ds2 = New DataSet
da2.Fill(ds2)
DataGridView3.DataSource = ds2.Tables(0)
MyConn2.Close()
Catch ex As Exception
If MyConn2.State <> ConnectionState.Closed Then MyConn2.Close()
End Try
This is supposed to retrieve all results where the date of the booking column is the same as the date today (the current date).
As it stands the datagridview throws up no errors but loads only the field names into the datagridview, not entries that meet the specification (entries with the current date).
Any help would be appreciated, thanks.
I think you need single quotes around the date
da2 = New OleDbDataAdapter("Select * from tbl_bookings WHERE DateOfBooking = "' & DateTime.Today & "'", MyConn2)
I have no knowledge of vb.net, but from the SQL side this could be caused because you are trying to compare a date value (e.g., 4/20/2015) with a date time value (e.g., 4/20/2015 at 11:57 AM). This kind of comparison will look at the time portion of the first date as midnight (4/20/2015 at 12:00 AM), and thus return no matches.
If any of the values in your table have times, or if your vb function returns a time other than midnight, try replacing your SQL with something like the following:
"Select *
from tbl_bookings
WHERE CAST(DateOfBooking AS DATE) = CAST('" & DateTime.Today & "' AS DATE)", MyConn2