How can i use multiple selects in ACCESS?
I want to do something like that:
New OleDbDataAdapter("SELECT * FROM Alunosescola", con) and ("SELECT * FROM Stock where Quantidade > 0", con)
But i dont know how i can do that in ACCESs.
Thank you
do you mean to Join the selects into one result?:-
MS Access Select Join
You can write :
New OleDbDataAdapter("SELECT * FROM Alunosescola LEFT JOIN Stock ON Alunosescola.AlunosescolaID = Stock.StockID where Stock.Quantidade > 0 ", con)
Related
I want to update the set sum but my code is not perfect, maybe I need to add or modify the sql.
I tried "UpdateTABLE2()" but the result is not yet in accordance with the output result I want
thanks
TABLE1
INVNO QTY PRICE DIS
1000 10 10000 10
1000 20 20000 20
1001 15 10000 10
1001 30 20000 20
TABLE2
INVNO TOTAL
1000
1001
OUTPUT
TABLE2
INVNO TOTAL
1000 410000 QTY*PRICE*(1-DIS/100) for total from INVNO 1000
1001 615000 QTY*PRICE*(1-DIS/100) for total from INVNO 1001
Private Sub fillDataGrid()
Try
Dim query As String = "SELECT INVNO,SUM((QTY*PRICE)*(1-DIS/100)) AS TOTAL FROM TABLE1 GROUP BY INVNO"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
'cmd.Parameters.AddWithValue("#CODE", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
da.Dispose()
source3.DataSource = dt
Me.DataGridView3.DataSource = source3
Me.DataGridView3.Refresh()
End Using
End Using
End Using
Catch ex As Exception
End Try
End Sub
Sub UpdateTABLE2()
Try
Dim sql As String = "UPDATE TABLE2 INNER JOIN TABLE1 ON TABLE1.[INVNO] = TABLE2.[INVNO] SET TABLE2.[TOTAL] = [QTY]*[PRICE]*(1-[DIS]/100)"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
'cmd.Parameters.AddWithValue("#INVNO", ComboBox1.SelectedValue)
conn.Open()
cmd.ExecuteNonQuery()
End Using
There are 3 problems to solve:
Calculate the total for each row in TABLE1. You could add a calculated field directly to the table, create a view that does it for you or do it with an inline WITH expression. I propose a view:
CREATE VIEW V_TABLE1
AS
SELECT *, (CAST(QTY AS MONEY) * CAST(Price AS MONEY) * (CAST(1 AS MONEY) - (CAST(DIS AS MONEY) / CAST(100 AS MONEY)))) AS Total FROM Table_1;
Group the data. Again, could be just a query or a view, here again as a view:
CREATE VIEW V_TABLE1_Consolidated
AS
SELECT NO, SUM(Total) AS Total FROM V_TABLE1
GROUP BY NO
Fill that into a table. Challenge yourself first whether it really needs to be serialized, and if that is a requirement, you could use something like the following code: (Watch out: It temporarily drops everything of TABLE2)
TRUNCATE TABLE TABLE2;
INSERT INTO TABLE2 SELECT * FROM V_TABLE1_Consolidated;
If you have additional data that you have omitted like an order number or a customer or a time range and the updates should only be refreshed for that order/customer/time range then you have to replace the TRUNCATE TABLE by a DELETE FROM TABLE2 WHERE ....
I need to display the customers that have purchased a product (based on a user search) in a list box. I have five different tables in Access which store different information and that relate to each other with IDs (using combox boxes in vb). I need to be able to search for a product, for example "White Bread", the program then should display the customer's full name and address as stored in the database.
Table: TransactionDetails
Fields: ID, stockID, custTransID
Table: CustomerTransaction
Fields: ID, custID, dateOfTransaction
Table: CustomerAccountDetails
Fields: ID, custFullName, custAddress, custLandline,
custMobile, custDOB, custCreditDetails
Table: StockDescription
Fields: ID, stockName, stockDesc, stockPrice
Table: SupplierDetails
Fields: ID, supplierName, supplier Address
I think I need to use INNER JOIN to query multiple tables at once but I am unsure of the syntax (I'm new to SQL). So far I have this:
Dim productSearch As String
productSearch = productSrchInput.Text
Dim databaseConnection As New OleDb.OleDbConnection
Dim counter As Integer
Dim array(10) As String
databaseConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=assignment5database.accdb"
databaseConnection.Open()
Dim searchDatabase As OleDbCommand = New OleDbCommand("SELECT CustomerAccountDetails.custFullName, CustomerAccountDetails.custAddress " & _
"FROM CustomerAccountDetails " & _
"INNER JOIN StockDescription ON TransactionDetails.stockID = TransactionDetails.custTransID " & _
"WHERE StockDescription.stockName = '" & productSearch & "'", databaseConnection)
Dim searchResults As OleDbDataReader = searchDatabase.ExecuteReader
counter = 1
Do While searchResults.Read
srchResultsList.Items.Add(searchResults.Item(0))
counter += 1
Loop
databaseConnection.Close()
You are missing some of the joins that connect the customer to the stock details. Here is the SQL that Access will expect in order to pull the data based on your description. The parentheses may seem extraneous, if you are used to SQL server or MySQL, but Access will throw a fit if you leave them out.
SELECT CustomerAccountDetails.custFullName, CustomerAccountDetails.custAddress, StockDescription.stockName
FROM StockDescription
INNER JOIN ((CustomerAccountDetails
INNER JOIN CustomerTransaction ON CustomerAccountDetails.ID = CustomerTransaction.custID)
INNER JOIN TransactionDetails ON CustomerTransaction.ID = TransactionDetails.custTransID) ON StockDescription.ID = TransactionDetails.StockID
WHERE StockDescription.stockName="something"
As noted by Fionnuala, I will almost always build a query that has multiple joins in it using the Access query designer before putting it in code. I almost always leave out a set of parentheses or try to write the query in a structure that SQL Server would expect and get rejected by Access.
I think you could be able to use an inner join but perhaps a "union" may be more efficient.
http://www.w3schools.com/sql/sql_union.asp is good for improving sql knowledge, it helped me a lot.
I have two saved queries in Microsoft Access called Current_Ratio and Quarterly_Growth_Rates. These two saved queries share the same Primary Key. But they may not all contain the same data. How do I use and Inner Join statement to show the data from these saved queries side by side?
Here is the code:
con.Open()
Dim cmd3 As OleDbCommand = New OleDbCommand("SELECT * FROM Current_Ratio AS C INNER JOIN Quarterly_Growth_Rates AS G ON (C.Ticker = G.Ticker) AND ((IIF(C.Period = 4, C.Year + 1, C.Year)) = G.Year) AND ((IIF(C.Period = 4, 1, C.Period + 1)) = G.Qtr)", con)
Dim reader As OleDbDataReader = cmd3.ExecuteReader()
Dim da As New DataTable
da.Load(reader)
DataGridViewCalculations.DataSource = da
reader.Close()
con.Close()
I get an error at da.Load(reader) saying:
The provider could not determine the Double value. For example, the row was just created, the default for the Double column was not available, and the consumer had not yet set a new Double value.
Additional Information:
I've been successfully running this code for a while now using an abbreviated set of data of approximately 15 stocks. I just scaled up the amount of data to approximately 6,000 stocks and now I am having this problem.
The problem is with the Current_Ratio query. If I run SELECT * FROM Current_Ratio I get the error. But not if I run SELECT * FROM Quarterly_Growth_Rates
I need help with my visual basic project. I have a Store.accdb database
which has 2 tables, customers and orders. I would like to be able to enter a customer's name (or part of a name) in a textbox and then display the name/s in a DataGridView when the search button is clicked. And then On a separate DataGridView I'd like to display the orders of the selected customer from my first DataGridView when the user clicks the Display button.
Edit: This is what the 2 tables look like
Customers table = custNum, custName, custAddress, custPhone
Orders table = orderNum, orderItem, custNum, price, qty
con.ConnectionString = dbProvider & dbSource
Try
con.Open()
sql = "SELECT custName FROM tblCustomers WHERE custName LIKE '%" & tbSearch.Text.ToUpper & "%'"
ds = New DataSet
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "CustomerDataset")
gridCustomers.DataSource = ds
gridCustomers.DataMember = "CustomerDataSet"
con.Close()
Catch ex As Exception
MessageBox.Show("Could not establish a connection", "Database Error")
End Try
This code works fine, it populates my customers datagridview. I get multiple rows whenever I only enter part of a customer's name. If I enter 'sm' in the textbox, it would display all customers with 'sm' in their name. How can I display the selected customer's (from 1st datagridview) orders in my 2nd datagridview when i click the display button? I hope I am making sense, english is not my first language so please bear with me.
Thanks!
You have to play with many events.
when selecting a customer from datagridview you have to use datagridview's selectedIndexChange event(assuming you have button to select in datagridview)
You have to use the same procedure in datagridview's selectedIndexChange event
con.ConnectionString = dbProvider & dbSource
Try
con.Open()
sql = "SELECT * FROM tblorders WHERE custName ='" & gridSelectedValue & "'"
//Assuming you have custName column in order table
ds = New DataSet
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "OrderDataset")
gridCustomers.DataSource = ds
gridCustomers.DataMember = "OrderDataset"
con.Close()
Catch ex As Exception
MessageBox.Show(ex.message)
End Try
Edit
If you dont have custName in order Then you should have CustNum in your query of DataGridView.
Step 1 - change the query that works. Instead of selecting just the customer name, select the customer id, or whatever the primary key of that table is.
Step 2 - when displaying your data, add an anchor tag with a query string that links to a new page showing the orders. The html should look like something like this:
Fred
In orders.aspx, call a query that brings back all the orders for customer_id = 1.
Oh, yes, by the way, convert all form and url variables to parameters before sending them to your database.
Actually, you only need to define a "Foreign Key" between the two tables, you can see this article to know how:
www.codeproject.com/Articles/28273/Xml-Database-Demo
Read the "Adding the DataTable Relation" section.
If you had made your db with Access, you have to the same thing. The same thing if you're using SQL.
I have a problem in showing data content from joined table in crystal report my sql query is good and it shown my own data but i when fill crystal report datasource and show it the crystal repeat duplicate and more data my code is:
Dim rep As CrystalReport1 = New CrystalReport1()
Dim objcon = New SqlConnection("data source=(local);initial catalog=hesabres;user id='sa';password='Maysam7026'")
Dim objcom = New SqlCommand
Dim objdata As New DataTable
Dim objdr As SqlDataReader
objcom.CommandText = " SELECT customer.customer_name, customer.customer_tel, orders.order_stuff_name, orders.order_number" & _ " FROM hesabres.dbo.orders orders inner JOIN hesabres.dbo.customer customer ON orders.order_customer_id=customer.customer_id"
objcom.Connection = objcon
objcon.Open()
objdr = objcom.ExecuteReader
objdata.Load(objdr)
rep.SetDataSource(objdata)
CrystalReportViewer1.ReportSource = rep
in fact may bought one chair and ball and jahan bought one ball!
Crystal reports does not show any data itself.
If your database query result is fine then their is something with their code.
I will suggest that please review your code in detail.
Apply distinct keyword in select statement as below and then check it
SELECT Distinct customer.customer_name, customer.customer_tel,
orders.order_stuff_name, orders.order_number" & _ "
FROM hesabres.dbo.orders orders
inner JOIN hesabres.dbo.customer customer
ON orders.order_customer_id=customer.customer_id