Where clause not working on a SQLite Join request - vb.net

I need all the unique values of ParteB field on ActPartB table matching the same IDNumber with userActTable but only for the condition of some userIDNumber (on userActTable)
The full sql string with the "WHERE"
sql = "SELECT DISTINCT ParteB FROM ActParteB INNER JOIN userAct ON IDNumber = IDNumber WHERE userAct.userIDNumber = ? order by ParteB asc"
Then I add
cmdConnection.Parameters.AddWithValue("#userIDNumber", NumberOfActiveuser)
The program run with no debugging error but it shows all the unique fields of ActPartB no matter the value of userIDNumber. The value os userIDNumber is fine because.
Is just that the WHERE is "ignored"
This
sql = "SELECT DISTINCT ParteB FROM ActParteB INNER JOIN userAct ON IDNumber = IDNumber WHERE userAct.userIDNumber = ? order by ParteB asc"
Produces the same ouput of this
sql = "SELECT DISTINCT ParteB FROM ActParteB INNER JOIN userAct ON IDNumber = IDNumber order by ParteB asc"
What is wrong with the Where clause?
Full code here:
Using conn As New SQLiteConnection(SQLiteConnStr)
Try
conn.Open()
Dim cmdConnection As SQLiteCommand = New SQLiteCommand(sql, conn)
Dim sql = "SELECT DISTINCT ParteB FROM ActParteB INNER JOIN userAct ON IDNumber = IDNumber WHERE userAct.userIDNumber = ? order by ParteB asc"
cmdConnection.Parameters.AddWithValue("#userIDNumber", NumberOfActiveUser)
Dim readerParteB As SQLiteDataReader = cmdConnection.ExecuteReader()
ParteBComboBox.Items.Clear()
Try
While (readerParteB.Read())
ParteBComboBox.Items.Add(readerParteB("ParteB"))
End While
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Using

Dim cmdConnection As SQLiteCommand = New SQLiteCommand(sql, conn)
Dim sql = "..."
Your command does not work correctly because it uses a different SQL string (the value of some other sql variable that you declared in some previous part of the code).
Furthermore, as mentioned by Jinx88909, you must add the table names to the join to specify which IDNumber column you mean (when in doubt, the database will of course choose the wrong one):
... JOIN userAct ON userAct.IDNumber = ActParteB.IDNumber ...
^^^^^^^^ ^^^^^^^^^^
Alternatively, when the column names are the same, better use USING, which automatically gets the column from both tables:
... JOIN userAct USING (IDNumber) ...

Related

'Syntax error in FROM clause' or 'Syntax error in JOIN operation' when joining two CSV files

I have two CSV files with baseball stats that I'm trying to join as follows,
SELECT
Master.playerID, Batting.RBI
FROM
([Master.csv] INNER JOIN [Batting.csv])
ON
(Master.playerID=Batting.playerID)
I've written a C# function to connect using Jet. I'm not having any trouble querying a single table (sample query SELECT COUNT(playerId) FROM [Master.csv] works fine), but for some reason it doesn't like the join.
Is it because the Master and Batting tables are unrecognized?
Relevant bits of my C# code attached,
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
FilePath + ";Extended Properties='text;HDR=Yes;FMT=Delimited;';";
OleDbConnection conn = new OleDbConnection(constr);
OleDbCommand command = new OleDbCommand(SQLStatement, conn);
conn.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
sda.Fill(dt);
sda.Dispose();
command.Dispose();
conn.Dispose();
The exception is thrown at the sda.Fill(dt) line and SQLStatement is simply the query string passed to the function as a string.
You add:
SELECT m.playerID, b.RBI
FROM [Master.csv] as m INNER JOIN
[Batting.csv] as b
ON m.playerID = b.playerID;
You may need a more advanced syntax to get at the files, but this fixes syntax errors.
The closing parenthesis on line 4 (the one with the two table names) should not be there. If you actually want to put parens the closing one has to be after the ON clause which in an intrinsic part of the JOIN syntax (not the FROM syntax):
SELECT
Master.playerID, Batting.RBI
FROM
([Master.csv] INNER JOIN [Batting.csv]
ON
(Master.playerID=Batting.playerID))
or, omitting the extra parentheses:
SELECT
Master.playerID, Batting.RBI
FROM
[Master.csv] INNER JOIN [Batting.csv]
ON
Master.playerID=Batting.playerID
which I would format as:
SELECT
Master.playerID, Batting.RBI
FROM
[Master.csv]
INNER JOIN [Batting.csv] ON Master.playerID=Batting.playerID

Is it possible to use a left outer join sql statement if column names are different in vb.net

I am working in VB.net 2013, windows form applications, and I need to do a left sided join sql statement, first time I have ever tried it. My question is, can you cross-reference two tables if the columns names are different but the data they have is the same. In my example I have tableA and tableB. TableA has a column named "JobNum" and TableB has the column named "JobNumber." Considering this is it still possible to do the join statement. Here is my code:
'load Job List
Try
'set/open sql connection
Using conn1 As New SqlConnection(connstring)
conn1.Open()
'Using comm1 As SqlCommand = New SqlCommand("Select JobNum, Shear from Production.dbo.[Floor Cell Jobs\Shears]", conn1)
Using comm1 As SqlCommand = New SqlCommand("SELECT JobNum FROM Production.dbo.[Floor Cells Jobs\Shears] LEFT OUTER JOIN Production.dbo.tblFCOrdered ON Production.dbo.[Floor Cells Jobs\Shears].JobNum = Production.dbo.fcOrdered.JobNumber", conn1)
'dim the variable rs as an sql datareader and execute that reader with sql comm1
Dim rs As SqlDataReader = comm1.ExecuteReader
'dim dt as a new datatable and load it into data set rs
Dim dt As DataTable = New DataTable
dt.Load(rs)
'set the combobox vale and display members
CBJob1.ValueMember = "JobNum"
CBJob1.DisplayMember = "JobNum"
'set the datasource for combobox CBJob1
CBJob1.DataSource = dt
End Using
End Using
Sure thing, you just do something like this
SELECT
*
FROM Table1 A
left join Table2 B on (A.JobNum = B.JobNumber)

Pass parameter to a query from another query in Access

I have a parameterized query GET_CUSTOMER:
SELECT * FROM Customer WHERE id = [customer_id]
I want to call this query from another query and pass it a parameter:
SELECT * FROM GET_CUSTOMER(123)
Note the above code is not valid, it is here to give you an idea of what I'm trying to do. Is it possible to do this in MS Access?
UPDATE 1:
The queries I posted are for example. The actual queries are much more complex. I know I can use table joins, but in my specific case it would be much easier if I could run parameterized queries inside other queries (that are parameterized as well). I can't use access forms because I'm using access with my .NET application.
This is how I end up solving this with help of https://stackoverflow.com/a/24677391/303463 . It turned out that Access shares parameters among all queries so there is no need to specifically pass parameters from one query to another.
Query1:
SELECT * FROM Customer WHERE ID > [param1] AND ID < [param2]
Query2:
SELECT * FROM Query1
VB.NET code:
Dim ConnString As String = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=Database.mdb"
Dim SqlString As String = "Query2"
Using Conn As New OleDbConnection(ConnString)
Using Cmd As New OleDbCommand(SqlString, Conn)
Cmd.CommandType = CommandType.StoredProcedure
Cmd.Parameters.AddWithValue("param1", "1")
Cmd.Parameters.AddWithValue("param2", "3")
Conn.Open()
Using reader As OleDbDataReader = Cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(reader("ID"))
End While
End Using
End Using
End Using
You can build the SQL on the fly.
MyID = prompt or get from user some ID
strSQl = "Select * from tblCustomer where ID in " & _
"(select * from tblTestCustomers where id = " & MyID
So you can nest, or use the source of one query to feed a list of ID to the second query.

Datagrid Duplication due to Select Statement VB

I am using an Access database, I believe the problem lies in my SQL statement. I have a relational database, with two tables -
StaffDetails [columns(
StaffID,
FirstName,
LastName)]
and
StaffTraining [columns(
StaffID,
Month)].
I have a combobox (cbMonth) and dependent on what month is chosen if the user selects 'January' then I would like the datagrid (DGTraining) to show the First Name and Last Name of the members of staff whose ID are within the chosen month. Sorry if this is not the clearest explanation, hopefully my code below makes my issue clearer:
Dim SqlQuery As String = "SELECT [StaffDetails.StaffID], [StaffDetails.FirstName], [StaffDetails.LastName], [StaffTraining.StaffID] FROM [StaffDetails], [StaffTraining] WHERE StaffTraining.TrainingMonth='" & cbMonth.Text & "'"
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "Training")
Dim dt As DataTable = ds.Tables("Training")
With DGTraining
.AutoGenerateColumns = True
.DataSource = ds
.DataMember = "Training"
End With
You are missing your join and are getting a cross join. 2 ways of addressing:
FROM [StaffDetails] inner join [StaffTraining] on [StaffDetails].staffID = [StaffTraining].staffID
That is the join logic thats more common and easier to read. You could add to your where clause (old method, harder to read and not as commonly accepted:
...where [StaffDetails].staffID = [StaffTraining].staffID and ...
Your last comment needs amending like this...
Dim SqlQuery As String = "SELECT [StaffDetails.StaffID], [StaffDetails.FirstName],
[StaffDetails.LastName], FROM [StaffDetails]
INNER JOIN [StaffTraining] ON [StaffDetails].StaffID = [StaffTraining].StaffID
WHERE [StaffTraining].TrainingMonth='" & cbMonth.Text & "'"
Also... dependant on how you have set up cbMonth you may want cbMonth.SelectedValue or cbMonth.SelectedText

Top Ten and Update

How do I run a query with VB that will return the TOP 10 results based on column appClickCount and update column appFAIList to 1 and anything below the TOP 10 will give the column appFAIList a value of 0?
Using sqlCon = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\ITCSDatabase.mdf;Integrated Security=True")
sqlCon.Open()
Dim sqlText = "SELECT top 10 appClickCount " & _
"FROM appTable" & _
"UPDATE appTable SET appFAIList = 1"
Dim cmd = New SqlCommand(sqlText, sqlCon)
cmd.ExecuteScalar()
End Using
Run this SQL statement instead
with t as (
select *, rn=row_number() over (order by 1/0)
from appTable)
update t set
appFAIList = case when rn<=10 then 1 else 0 end
Your vb.net code is quite buggy though. You're using ExecuteScalar which is intended to return a single-row, single-column result. As written, it will give you the first appClickCount value.
The other issue is that using TOP 10 in SQL Server without a corresponding ORDER BY means that it will quite arbitrarily (aka "randomly") return any 10 records from the table.
UPDATE a
SET a.appFAIList = 1
FROM appTable AS a
INNER JOIN
(SELECT top 10 appClickCount FROM appTable) AS b ON a.SomeField = b.SomeField
SomeField - may be primary key of your table