I have a ComboBox named ComboBox_Calculations in my program that is filled with calculations (ex. Current_Ratio, Total_Debt_To_Assets_Ratio). ComboBox_Calculations is actually populated by using the contents of a field in a tabled called Criteria in my Access Database.
I need to create a saved query called Calculations_Quarterly. The query needs to have fields of Ticker, [Year], Period and then one field for every item in ComboBox_Calculations. So for this example I would also need fields named Current_Ratio and Total_Debt_To_Assets_Ratio.
Here is what my tables look like so far:
Criteria
Calculations_Quarterly
Here is the code I have that adds one field at a time (in this case Current_Ratio. But I do not know how add a column for every item in ComboBox_Calculations
con.Open()
Dim dr As OleDbDataReader
Dim cmd6 As New OleDb.OleDbCommand("SELECT Calculation, [Interval], Formula FROM Criteria", con)
dr = cmd6.ExecuteReader
dr.Read()
Dim Calculation = dr("Calculation").ToString
Dim Interval = dr("Interval").ToString
Dim Formula = dr("Formula").ToString
Dim Where_Statement As String
If Interval = "Daily" Then
Where_Statement = "WHERE Historical_Stock_Prices.[Date] < " & DateTime.Now.Date & ""
ElseIf Interval = "MRQ" Then
Where_Statement = "WHERE Income_Statements.Period < 5"
ElseIf Interval = "TTM" Then
Where_Statement = "WHERE Income_Statements.Period < 5"
ElseIf Interval = "5 Year" Then
Where_Statement = "WHERE Income_Statements.Period = 5"
Else
Where_Statement = ""
End If
Try
Dim cmd2 As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)
cmd2.ExecuteNonQuery()
Catch ex As Exception
Finally
Dim cmd2a As OleDbCommand = New OleDbCommand("DROP PROCEDURE " & Calculation & "", con)
cmd2a.ExecuteNonQuery()
Dim cmd2b As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)
cmd2b.ExecuteNonQuery()
End Try
con.Close
I couldnt find the name of you combobox or how it is filled so assuming it is named Combo1, and you filled it using Combo1.Items.Add("..."), you would want something like this:
Dim sb as new System.Text.StringBuilder("")
For each s as string in Combo1.Items
sb.Append("," & s)
Next
And then in your SQL:
Dim cmd2 As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & sb.ToString & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)
Related
I am using a select statement to retrieve records from an ms access table between two dates and another condition to check for customers name
I get the error "No value given for one or more required parameters"
The code is as below
Try
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
Dim dtDate1 As DateTime = DateTime.Parse(dtpDateFrom.Text)
Dim dtDate2 As DateTime = DateTime.Parse(dtpDateTo.Text)
''''SQL_PaymentsP = "SELECT InvoiceID,CustomerName,InvoiceDate,InvoiceAmount,PaymentDesc,PaidAmount,DatePaid,CurrentBalance FROM Payments WHERE [DatePaid] BETWEEN #" & dtDate1.ToString("MM/dd/yyyy") & "# AND #" & dtDate2.ToString("MM/dd/yyyy") & "# " & "OR [CustomerName] = " & txtCustomer.Text & ""
SQL_PaymentsP = "SELECT Payments.PaymentID, Payments.InvoiceID, Payments.CustomerName, Payments.InvoiceDate, Payments.InvoiceAmount, Payments.PaymentDesc, Payments.PaidAmount, Payments.DatePaid, Payments.CurrentBalance, Payments.Status FROM Payments WHERE Payments.DatePaid Between #" & dtDate1.ToString("MM/dd/yyyy") & "# And #" & dtDate2.ToString("MM/dd/yyyy") & "# " & " OR " & "Payments.CustomerName =" & txtCustomer.Text & ""
' SQLInvoicesP = "Select DateInvoice,IDInvoices,InvoiceAmount,CustomerName,Mode from Invoices where DateInvoice between #" & dtDate1.ToString("MM/dd/yyyy") & "# and #" & dtDate2.ToString("MM/dd/yyyy") & "#"
DataSet_PaymentsP.Clear()
Dim DataAdapter_PaymentsP As New OleDbDataAdapter(SQL_PaymentsP, Conn)
DataAdapter_PaymentsP.Fill(DataSet_PaymentsP, "Payments")
Conn.Close()
Application.DoEvents()
Dim ConInfo As New CrystalDecisions.Shared.TableLogOnInfo
ConInfo.ConnectionInfo.ServerName = Application.StartupPath & "\DB.mdb"
ConInfo.ConnectionInfo.DatabaseName = "kuku.mdb"
ConInfo.ConnectionInfo.UserID = "Admin"
ConInfo.ConnectionInfo.Password = ""
Dim rpt1 As New CrystalReport5
rpt1.Database.Tables(0).ApplyLogOnInfo(ConInfo)
rpt1.SetDataSource(DataSet_PaymentsP)
rpt1.SetParameterValue("Start_Date", dtDate1)
rpt1.SetParameterValue("End_Date", dtDate2)
rpt1.SetParameterValue("CustomerName", txtCustomer.Text)
rpt1.SetParameterValue("Author", FormMain.XN.Text)
Dim frm As New FormPrint
frm.CrystalReportViewer1.ReportSource = rpt1
frm.CrystalReportViewer1.LogOnInfo(0).ConnectionInfo.Password = "yazsys.com1234"
frm.ShowDialog()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
I just did add the single quotation marks as shown below and the select query can now retrieve records fro ms access
SQL_PaymentsP = "SELECT Payments.PaymentID, Payments.InvoiceID,
Payments.CustomerName, Payments.InvoiceDate, Payments.InvoiceAmount,
Payments.PaymentDesc, Payments.PaidAmount, Payments.DatePaid, Payments.CurrentBalance, Payments.Status FROM Payments WHERE Payments.DatePaid Between '#" & dtDate1.ToString("MM/dd/yyyy") & "#' And '#" & dtDate2.ToString("MM/dd/yyyy") & "#' OR " & "Payments.CustomerName ='" & txtCustomer.Text & "'"
I have a search button which looks up for data only in tblDopage but there is a field strMatrice in this table that is linked to table tblMatrice. So if the user is searching for Matrice I should retrieve Matrice from tblMatrice and innerjoin it with tblDopage on strMatrice, it's like a search inside search and the result of searching for matrice is more than 1 result so that I have many results which i should link them with tblDopage to display the final result. What shall i do, I spended 3 days searching for a solution.
I retrieved strMatrice from tblMatrice and populated a dataset with the result but I don't know how to innerjoin between a dataset and table in the database which is the tblDopage
Help is very appreciated, Thank you in advance
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim sql = "SELECT * from tblDopages WHERE "
cmd = New OleDbCommand(Sql, myConnection)
Dim da As OleDbDataAdapter
If CKBrefech.Checked = True Then
sql = sql & "strRefEch = '" & TBrefech.Text & "' AND "
End If
If CKBmethode.Checked = True Then
sql = sql & "strMethode = '" & CBmethode.Text & "' AND "
End If
If CKBpurif.Checked Then
sql = sql & "strPurif = '" & CBpurif.Text & "' AND "
End If
If CKBmatrice.Checked Then
sql = sql & "strMatrice = '" & CBmatrice.Text & "' AND "
End If
If CKBmol.Checked Then
sql = sql & "strMolecule = '" & CBmol.Text & "' AND "
End If
If CKBechprep.Checked Then
sql = sql & "datDatePrepa >= #DatPrepa AND "
cmd.Parameters.Add("#DatPrepa", OleDbType.Date).Value = DTPechprep.Value.Date
End If
If CKBechau.Checked Then
sql = sql & "datDatePrepa <= #Datau AND "
cmd.Parameters.Add("#Datau", OleDbType.Date).Value = DTPechau.Value.Date
End If
If CKBtrigprepa.Checked = True Then
sql = sql & "strTrigPrepa = '" & TBtrigprepa.Text & "' AND "
End If
If CKBtriganaly.Checked = True Then
sql = sql & "strTrigAnaly = '" & TBtrigAnaly.Text & "' AND "
End If
If CKBappar.Checked = True Then
sql = sql & "strNomTech = '" & CBappar.Text & "' AND "
End If
If CKBnumappar.Checked = True Then
sql = sql & "[strEquip(Appareil)] = '" & CBnumappar.Text & "' AND "
End If
If CKBteneurmini.Checked = True Then
sql = sql & "dblDopage >= " & TBteneurmini.Text & " AND "
End If
If CKBteneurmax.Checked = True Then
sql = sql & "dblDopage <= " & TBteneurmax.Text & " AND "
End If
'if referentiel is enabled
myConnection.Close()
If CKBnomref.Checked Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
'Get IDref from table tblRefMatDetails and then make an innerjoin with tblRefMatrice to retrieve the matrice and insert it into the search query of tblDopages
Dim query = "select distinct a.strMatrice from tblRefMatrice a INNER JOIN tblRefMatDetails b on a.intIDref=b.intIDRef where "
cmd = New OleDbCommand(query, myConnection)
Try
If CKBnomref.Checked Then
query = query & "b.strReferentiel = '" & CBnomref.Text & "' AND "
End If
If CKBniv1.Checked Then
query = query & "b.strNIveau1 = '" & CBniv1.Text & "' AND "
End If
If CKBniv2.Checked Then
query = query & "b.strNiveau2 = '" & CBniv2.Text & "' AND "
End If
If CKBniv3.Checked Then
query = query & "b.strNiveau3 = '" & CBniv3.Text & "' AND "
End If
If CKBniv4.Checked Then
query = query & "b.strNiveau4 = '" & CBniv4.Text & "' AND "
End If
' Remove the last AND if any ....'
If query.EndsWith(" AND ") Then
query = query.Substring(0, query.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If query.EndsWith(" WHERE ") Then
query = query.Substring(0, query.Length - 7)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
cmd.CommandText = query
cmd.Connection = myConnection
Dim MyDataTable As New DataTable
Dim da As New OleDbDataAdapter(query, myConnection)
da.Fill(MyDataTable)
Dim row As DataRow
For Each row In MyDataTable.Rows
Dim strMatrice As String
strMatrice = row("strMatrice")
Next row
DataGridView2.DataSource = MyDataTable
'to focus on first row of DGV after populating it
DataGridView2.Rows(0).Selected = True
myConnection.Close()
Dim matrice As String
For x As Integer = 0 To DataGridView2.Rows.Count - 2
matrice = DataGridView2.Rows(x).Cells(0).Value
sql = sql & " strMatrice = '" & matrice.ToString & "' AND "
Dim row As DataRow
For Each row As DataRow In MyDataTable.Rows
matrice = row.Item("Detail")
Next row
Next
End If
' Remove the last AND if any ....'
If sql.EndsWith(" AND ") Then
sql = sql.Substring(0, sql.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If sql.EndsWith(" WHERE ") Then
sql = sql.Substring(0, sql.Length - 7)
End If
' cmd = New OleDbCommand(sql, myConnection)
cmd.CommandText = sql
cmd.Connection = myConnection
Dim MyDataSet As New DataSet
da = New OleDbDataAdapter(sql, myConnection)
da.SelectCommand = cmd
da.SelectCommand.Parameters.Add(New OleDbParameter("#DatPrepa", DTPechprep.Value)) 'adding date parameters to datatable
da.SelectCommand.Parameters.Add(New OleDbParameter("#datau", DTPechprep.Value)) 'adding date parameters to datatable
'da.SelectCommand.Parameters.Add(New OleDbParameter("#Matrice", matrice.ToString)) 'adding Matrice parameters to datatable
da.Fill(MyDataSet, "Matrice")
DataGridView1.DataSource = MyDataSet.Tables("Matrice")
'to focus on first row of DGV after populating it
DataGridView1.Rows(0).Selected = True
LBnumresult.Text = DataGridView1.RowCount - 1
I have converted my database from Access to Sql as Sql didn't accept format() so is displaying an error.
This is my code:
DefaultStr = "" &
"SELECT StudentAccount.Dated, StudentAccountS.StAdmNo, StudentAccountS.StClass, " &
"StudentAccountS.StName, StudentAccount.Perticular, StudentAccount.Amount,StudentAccount.Remark,StudentAccount.PayMode,TransactionID " &
"FROM (StudentAccount LEFT OUTER JOIN StudentAccountS ON StudentAccount.SSID = StudentAccountS.SSID) " &
"WHERE (StudentAccount.Debit) and (StudentAccount.Dated Between " &
"#" & Format(DateFrom, "MM/dd/yyyy") & "# AND #" & Format(DateTo, "MM/dd/yyyy") & "#)"
Select Case SIndex
Case 0
SelStr = " AND (StudentAccount.PayMode = '" & OptionStr & "') Order By StudentAccount.Dated"
Case 1
SelStr = " AND (StudentAccount.Perticular = '" & OptionStr & "') Order By StudentAccount.Dated"
Case 2, 3
SelStr = " AND (StudentAccount.TransType = '" & filterStr & "') Order By StudentAccount.Dated"
Case Else
SelStr = Nothing
End Select
Da = New SqlDataAdapter(DefaultStr & SelStr, Conn)
Ds = New DataSet
Da.Fill(Ds)
You have to use something like this:
Dim CMD As SqlClient.SqlCommand = Conn.CreateCommand
Dim dtStart As DateTime = New DateTime(2015, 9, 6, 10, 1, 0)
Dim dtEnd As DateTime = New DateTime(2015, 9, 6, 11, 0, 0)
CMD.CommandText = "SELECT * FROM Table1 WHERE Date BETWEEN '" & dtStart.ToString("yyyy-MM-dd HH:mm:ss") & "' AND '" & _
dtEnd.ToString("yyyy-MM-dd HH:mm:ss") & "'"
Dim DA As New SqlClient.SqlDataAdapter
DA.SelectCommand = CMD
Dim DT As New DataTable
DA.Fill(DT)
Howewer i suggest you to start learing SqlParameter for queries (that are much more reliable, as for example in dealing with sql injection). Simply use something like that:
CMD.Parameters.Add("#DateStart", SqlDbType.DateTime2, 20).Value = dtStart
CMD.Parameters.Add("#DateEnd", SqlDbType.DateTime2, 20).Value = dtEnd
CMD.CommandText = "SELECT * FROM Table1 WHERE Date BETWEEN #DateStart AND #DateEnd"
I want to fetch data from a database that falls between two dates.
The code:
con1.Open()
Dim re As String = ""
Dim d1 As DateTime = DateTimePicker2.Value.ToString("dd/MM/yyyy")
Dim d2 As DateTime = DateTimePicker3.Value.ToString("dd/MM/yyyy")
Dim cmd As New OleDbCommand("Select lno,pname,mdue,ramt from Due where ddate >= '" + Convert.ToDateTime(d1) + "' and ddate<= '" + Convert.ToDateTime(d2) + "' and ramt='0'", con1)
Dim da As OleDbDataReader = cmd.ExecuteReader
While (da.Read())
re = re & " " & da("lno").ToString.PadRight(30) & " " & da("pname").ToString.PadLeft(10) & " " & da("mdue").ToString.PadLeft(10) & Chr(13)
End While
I get a data type mismatch error. The datatype for date is Date/Time only.
You are converting to string before assiging to your DateTime variables!
Try
con1.Open()
Dim re As String = ""
Dim d1 As DateTime = DateTimePicker2.Value
Dim d2 As DateTime = DateTimePicker3.Value
Dim cmd As New OleDbCommand("Select lno,pname,mdue,ramt from Due where ddate >= #" & String.Format("{0:dd/MM/yyyy}", d1) & "# and ddate<= #" & String.Format("{0:dd/MM/yyyy}", d2) & "# and ramt='0'", con1)
Dim da As OleDbDataReader = cmd.ExecuteReader
While (da.Read())
re = re & " " & da("lno").ToString.PadRight(30) & " " & da("pname").ToString.PadLeft(10) & " " & da("mdue").ToString.PadLeft(10) & Chr(13)
End While
You should also probably use & as the concatenation operator ... https://msdn.microsoft.com/en-us/library/te2585xw.aspx
This is my code for populating the datagridview:
Public Sub generate_list_ftMK(ByVal clbBranch As CheckedListBox, ByVal dtpSDate As DateTimePicker, ByVal dtpEDate As DateTimePicker, ByVal dvList As DataGridView)
Dim ds As DataSet = New DataSet()
Dim da As MySqlDataAdapter
Dim strQ As String = String.Empty
Dim strQ1 As String = String.Empty
Dim colItemCode As String = String.Empty
Dim colReg_Pri As String = String.Empty
Dim colXL_Pri As String = String.Empty
Dim colDel_Date As String = String.Empty
Dim colLabel As String = String.Empty
Dim colDays As String = String.Empty
Dim PCT As String = String.Empty
Try
If con.State = ConnectionState.Open Then con.Close()
con.Open()
'clear the dataset
ds.Tables.Clear()
'loop for all branches
For i = 0 To clbBranch.CheckedItems.Count - 1
Application.DoEvents()
'get the Branch Code
chkBranch = clbBranch.CheckedItems(i).ToString
'select item code and price where JO_TYPE is JO
strQ = "select " & _
"CONCAT(a.STYLE_CODE, '-', LPAD((a.JO_NO), 4, '0'), '-', d.LINE_NO) as Item_Code, " & _
"DATE_FORMAT(c.DEL_DATE, '%Y-%m-%d') as DEL_DATE, " & _
"d.REG_PRI as Reg_Price, " & _
"d.XL_PRI as XL_Price, " & _
"a.LABEL_CODE, " & _
"a.STYLE_CODE, " & _
"LPAD((a.JO_NO), 4, '0')," & _
"d.LINE_NO, " & _
"DATEDIFF('" & Format(Date.Now, "yyyy-MM-dd") & "',DATE_FORMAT(c.DEL_DATE, '%Y-%m-%d')) as Days " & _
"from " & _
"jo_hdr as a " & _
"inner join " & _
"branch as b ON a.BRNCH_CODE = b.BRNCH_CODE " & _
"inner join " & _
"dr_hdr as c ON c.TRAN_REF = a.TRAN_NO " & _
"inner join " & _
"dr_det as d ON d.DR_NO = c.DR_NO " & _
"where " & _
"c.DEL_DATE BETWEEN '" & dtpSDate.Text & "' AND '" & dtpEDate.Text & "' " & _
"and a.LABEL_CODE = '" & FtMK_Code & "' " & _
"and a.BRNCH_CODE = '" & chkBranch & "' " & _
"and SUBSTRING(d.REG_PRI,LENGTH(d.REG_PRI) - 1,2) = 75 " & _
"and SUBSTRING(d.REG_PRI,LENGTH(d.XL_PRI) - 1,2) = 75 "
cmd = New MySqlCommand(strQ, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "tblJO")
For r = 0 To ds.Tables("tblJO").Rows.Count - 1
Application.DoEvents()
colItemCode = ds.Tables("tblJO").Rows(r)(0).ToString
colDel_Date = ds.Tables("tblJO").Rows(r)(1).ToString
colReg_pri = ds.Tables("tblJO").Rows(r)(2).ToString
colXL_pri = ds.Tables("tblJO").Rows(r)(3).ToString
colLabel = ds.Tables("tblJO").Rows(r)(4).ToString
sumStyle = ds.Tables("tblJO").Rows(r)(5).ToString
sumJO = ds.Tables("tblJO").Rows(r)(6).ToString
sumNo = ds.Tables("tblJO").Rows(r)(7).ToString
colDays = ds.Tables("tblJO").Rows(r)(8).ToString
'for the number to decimal
colReg_pri = FormatNumber(colReg_pri, 2)
colXL_pri = FormatNumber(colXL_pri, 2)
'get the total quantity and the branch quantity
get_TotalQty_and_BranchQty()
'if the branch quantity is zero
If branchQty = 0 Then
PCT = "N\A"
Else
'compute the percent sold
PCT = totalQty
End If
dvList.Rows.Add(False, colItemCode, PCT, colDel_Date, Format(Date.Now, "yyyy-MM-dd"), colDays, _
colReg_Pri, colXL_Pri, colLabel, "JO", dtpSDate.Text, dtpEDate.Text, _
clbBranch.CheckedItems(i).ToString, mkType)
Next
Next
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
I have use indexes in my tables, and also add application.doevents. Is there anything I could do to make the populating in the datagridview faster with this code? I'm trying to search about making the datagridview doublebuffered because I read it online that I will make the datagridview faster but I have no idea how to use it.
Any help will be appreciated, Thank you.
Your issue is using
Application.DoEvents
I'm not going to get into the details of why this is bad practice, try using a Background Worker instead.