Error on SQL Inner Join Statement - sql

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

Related

UPDATE SET SUM IN SQL FROM ANOTHER TABLE IN VB.NET

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 ....

Distinct values with MAX and MIN from Access Database in VB NET

I am trying to help HR by arranging the time attendance data from biometric readers in a more readable way. The output from the readers are summarized in a Access database. The output looks like the image bellow:
Each employee can have 1 IN and 1 EXIT daily (f_ReaderName column ). Some of them swipe the card multiple times and multiple INs or EXITs are recorded. How can I query the database or arrange this programmatically to have, per each Data column value, a single record for each f_CardNO and 2 columns: a MAX of Ora where f_ReaderName = 1-1[In] and a MIN of Ora where f_ReaderName = 1-1[Exit]?
Is it any way I can achieve this? A hint will be more than useful. Thanks a bunch!
LE: Manage to get to this query, but cannot be parsed, what am I doing wrong in the syntax:
SELECT
CR.f_CardNO,
Format(CR.f_ReadDate, 'Short Date') AS Data,
CR.f_ConsumerName,
CR.f_GroupName,
CR.f_ReaderName,
(
SELECT
ISNULL(MAX(FORMAT(CR.f_ReadDate, 'Long Time')), 0) AS Expr1
FROM
v_d_CardRecord CR1
WHERE
(
CR.f_ReadDate = CR1.f_ReadDate
AND CR.CardNO = CR1.CardNO
AND CR1.F_ReaderName = # 1 - 1[In] #
)
)
As OraIntrare,
(
SELECT
ISNULL(MIN(FORMAT(CR.f_ReadDate, 'Long Time')), 0) AS Expr1
FROM
v_d_CardRecord CR1
WHERE
(
CR.f_ReadDate = CR1.f_ReadDate
AND CR.CardNO = CR1.CardNO
AND CR1.F_ReaderName = # 1 - 1[Exit] #
)
)
As OraIesire
FROM
v_d_CardRecord CR
WHERE
(
CR.f_ReadDate > # 12 / 1 / 2016 #
)
ORDER BY
CR.f_ConsumerName,
Format(CR.f_ReadDate, 'Short Date')
GROUP BY
CR.f_CardNO,
Data,
CR.f_ConsumerName,
CR.f_GroupName,
CR.f_ReaderName,
OraIntrare,
OraIesire
This is my code in Visual Basic in Distinct Database. Correct me if i'm wrong.
You can put this on form load. I think this is for combobox only. (not sure) but it works in my combobox it distinct my database.
Dim da As New OleDbDataAdapter("select distinct [FULL NAME] from
EmpInfo", con1)
Dim table As New DataTable()
da.Fill(table)
ComboBox1.DataSource = New BindingSource(table, Nothing)
ComboBox1.DisplayMember = "FULL NAME"

How can i use multiple selects in ACCESS vb.net

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)

How to inner join two already filled DataTables in VB.NET

I marked Der Golem's answer as correct as it was the right answer for the specific problem I said I was having.
Unfortunately, I failed to detect the fact that the records in datatable2 aren't unique, which obviously doesn't jive well with performing an "inner join" on the two tables for the result I was wanting.
Setting a DataRelation would work if it was.
I'm still new to VB.NET, so please bear with me.
I have two data tables, each filled from different database servers.
They both have three columns (for ease of testing, final program will have 50+).
They both have a common data column that I want to inner join by ("OrderNum").
There's a question here, but the "answer" doesn't work for me, nor the LINQ option below it:
Merging 2 data tables in vb.net
This is my example code:
DB1 = New DatabaseConnectionSQL1
DB1.OpenConn()
DB2 = New DB_DatabaseConnectionSQL2
DB2.OpenConn()
Dim dtA As DataTable = New DataTable("DataTable1")
Dim dtB As DataTable = New DataTable("DataTable2")
Dim dtCombined As DataTable = New DataTable("CombinedDataTable")
dtA.Columns.Add("Order", System.Type.GetType("System.String"))
dtA.Columns.Add("Account_Number", System.Type.GetType("System.String"))
dtA.Columns.Add("Account_Name", System.Type.GetType("System.String"))
'"Order" = "Head_Order_Number"
dtB.Columns.Add("Head_Order_Number", System.Type.GetType("System.String"))
dtB.Columns.Add("Line_Number", System.Type.GetType("System.Int32"))
dtB.Columns.Add("Model", System.Type.GetType("System.String"))
dtA = DB1.GetDataTable(sQuery1)
dtB = DB2.GetDataTable(sQuery2)
'This doesn't work as it just appends the table
'dtA.Merge(dtB, True)
'I tried creating a DataSet and setting a Relation, but that kept failing
'I've tried at least 10 different things here. I'm at my wit's end.
dgvDataGrid.DataSource = dtCombined
dgvDataGrid.Refresh()
DB1.CloseConn()
DB2.CloseConn()
I noticed people in other places are suggesting using Linq. Even though I'm not familiar with it, I tried my best and kept failing.
Table A (dtA):
Order | Account_Number | Account_Name
10000 | 10000000000001 | BlahA
20000 | 10000000000002 | BlahB
30000 | 10000000000003 | BlahC
Table B (dtB):
Head_Order_Number| Line_Number | Model
10000 | 00000000034 | MD35Z
15000 | 00000000530 | MX25A
25000 | 00000024535 | P231Y
20000 | 00000027735 | A511L
30000 | 00000000910 | M232C
Final table I want combining the two (dtCombined):
Order | Account_Number | Account_Name | Line_Number | Model
10000 | 10000000000001 | BlahA | 00000000034 | MD35Z
20000 | 10000000000002 | BlahB | 00000027735 | A511L
30000 | 10000000000003 | BlahC | 00000000910 | M232C
Any help would be greatly appreciated.
I tried adding a DataRelation before and kept getting an error, but I wasn't setting something up properly. Now that I fixed that problem, I'm getting another error:
"System.ArgumentException: This constraint cannot be enabled as not all values have corresponding parent values."
dt1 = New DataTable("DataTable1")
dt1.Columns.Add("order_number", System.Type.GetType("System.String"))
dt1.Columns.Add("account_name", System.Type.GetType("System.String"))
dt2 = New DataTable("DataTable2")
dt2.Columns.Add("head_order_number", System.Type.GetType("System.String"))
dt2.Columns.Add("model", System.Type.GetType("System.String"))
Conn1.ConnectionString = sConnString1
Dim da1 As SqlDataAdapter = New SqlDataAdapter(sQuery1, Conn1)
Conn1.Open()
Conn2.ConnectionString = sConnString2
Dim da2 As SqlDataAdapter = New SqlDataAdapter(sQuery2, Conn2)
Conn2.Open()
ds = New DataSet
da1.Fill(ds, "DataTable1")
da2.Fill(ds, "DataTable2")
Dim dr As DataRelation = New DataRelation("Combined", _
ds.Tables("DataTable1").Columns("OrderNo"), _
ds.Tables("DataTable2").Columns("OrderNo"))
ds.Relations.Add(dr)
dgvDataGrid.DataSource = ds
dgvDataGrid.Refresh()
Conn1.Close()
Conn2.Close()
That error seems to make sense, as DataTable1 has 1950 total rows, while DataTable2 has over 4000, but isn't that the point of the DataRelation? It effectively inner joins the two tables so the end result should be 1950 rows?
The query you want to execute looks like this one:
Dim sql As String = "SELECT dta.*, dtB.* FROM dtA INNER JOIN dtB ON dtA.Order = dtB.Order"
Please note that the record with Order = 25000 is not part of the INNER JOIN
[EDIT]
As per your comment, I see you lack some knowldge...
So - ASSUMING you already have your db connection prepared (conn):
Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)
Dim da As OleDbDataAdapter = New OleDbDataAdapter
da.SelectCommand = cmd
conn.Open()
Dim ds As DataSet = New DataSet
da.Fill(ds, "Result")
conn.Close()
dgvDataGrid.datasource = ds
ds.DataBind()
I'm assuming an OleDb Connection - But a SQL connection is really the same (replace OleDb with Sql)
[EDIT 2] You decided to make me sweat!
Finally, there's a solution for your very specific problem:
As shown here: http://msdn.microsoft.com/en-us/library/cc188919.aspx
The DataRelation object is what you need.
Creating DataRelation Objects
' Create the DataRelation and
' relate the customers to their orders
DataRelation oDr_Customer2Order = new DataRelation("Customer2Order",
oDs.Tables["Customer"].Columns["CustomerID"],
oDs.Tables["Order"].Columns["CustomerID"]);
oDs.Relations.Add(oDr_Customer2Order);
By creating the DataRelation objects and then adding them to the DataSet's Relations collection, the three DataTable objects' rowsets are related to one another through the defined fields. Like most of the ADO.NET objects, the DataRelation object has several different constructors. I used the constructor that accepts the name of the relation, the parent table's column, and the child table's column. If there were multiple columns that define the relationship, I could have passed in an array of the parent table's columns and an array of the child table's columns. Another option is to use the same first three parameters that I used in Figure 3 and then pass in a fourth parameter to represent whether the constraints should be created automatically (pass in a Boolean value). But more on constraints in a moment.
Once the DataSet is filled with the three rowsets and the relations are established linking the DataTable objects, the DataSet could easily be displayed in a DataGrid on a Web Form by setting the DataSource property like this:
dataGrid1.DataSource = oDs;
The DataGrid is clever enough to figure out that there are multiple DataTable objects that need to be displayed and that it should allow the rowsets to be navigated in the order that's prescribed by the DataRelation objects.

crystal report and sql commands

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