I have 2 tables, products, and author, the author table has a column that relates to the product table by an ID so I have done a select statement below to get the right rows based on the ID's. However the author table might not have any data in and therefore no ID to the product table. If this is the case then the information from the product doesn't show up.
So my question is how do i handle this?
Dim ID As String = Request("id")
If String.IsNullOrEmpty(ID) Then
Response.Redirect("/Default.aspx")
End If
Try
Using conn As New OleDbConnection(strcon)
conn.Open()
Dim cmd As String = "SELECT * FROM tblProducts, tblPrdAuthor " & _
"WHERE tblProducts.ID = " & ID & " AND tblPrdAuthor.paPrdID = tblProducts.ID"
Using da As New OleDbDataAdapter(cmd, conn)
Dim ds As New DataSet()
da.Fill(ds)
'Bind to the repeater
rptProduct.DataSource = ds
rptProduct.DataBind()
End Using
End Using
Catch ex As Exception
Throw ex
End Try
Thank you!
Select * from table1 as A left outer join table2 as B on (A.id=B.id) where a.id=101 and b.pid=102
Related
I wanted to do the sql command "select DISTINCT" but it didn't work if there was another solution. I have four tables namely GSDTS, GSGTS, STFTS and TEMPTABL.
Thanks
error
Private Sub PopulateComboBox()
Dim query As String = "SELECT DISTINCT PNM FROM GSDTS"
Try
Using con As OleDbConnection = New OleDbConnection(cn)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
'Fill the DataTable with records from Table.
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
'Insert the Default Item to DataTable.
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
'Assign DataTable as DataSource
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "PNM"
ComboBox1.ValueMember = "PNM"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
you neeed to cnage the query to
SELECT DISTINCT PNM FROM GSDTS
UNION
SELECT DISTINCT PNM FROM GSGTS
UNION
SELECT DISTINCT PNM FROM STFTS
UNION
SELECT DISTINCT PNM FROM TEMPTAB
ORDER BY PNM
the DISINCT will only take UNIQUE OMN and the UNION will take care of all duplicates.
But you will so never know,. which PMN belongs to which table.
Dim cmd As New SqlCommand("SELECT MainDepartmentsTable.ID, FeesTable.ID,FeesTable.Particular,FeesTable.Fee from MainDepartmentsTable inner join SubDepartmentsTable on MainDepartmentsTable.ID = SubDepartmentsTable.MainDeptID inner join FeesTable on SubDepartmentsTable.MainDeptID = FeesTable.SubDepartmentID WHERE FeesTable.ID = '" & TextDepartmentID.Text & "' ", con)
Dim DataAdopter = New SqlDataAdapter(cmd)
Dim dt As New DataTable
DataAdopter.Fill(dt)
Load_Deparments()
First you need to validate the user input.
Using blocks ensure that you connection and command are closed and disposed.
Parameters save your database from sql injection. I had to guess at the datatype.
Private ConStr As String = "Your connection string"
Private Sub OPCode()
Dim DeptID As Integer
If Not Integer.TryParse(TextDepartmentID.Text, DeptID) Then
MessageBox.Show("Please enter a valid department ID.")
Exit Sub
End If
Dim dt As New DataTable
Using con As New SqlConnection(ConStr),
cmd As New SqlCommand("SELECT MainDepartmentsTable.ID,
FeesTable.ID,
FeesTable.Particular,
FeesTable.Fee
from MainDepartmentsTable
inner join SubDepartmentsTable on
MainDepartmentsTable.ID = SubDepartmentsTable.MainDeptID
inner join FeesTable on
SubDepartmentsTable.MainDeptID = FeesTable.SubDepartmentID
WHERE FeesTable.ID = #DepartmentID;", con)
cmd.Parameters.Add("#DepartmentID", SqlDbType.Int).Value = DeptID
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
Load_Departments(dt)
End Sub
Private Sub Load_Departments(dt As DataTable)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "Particular"
ComboBox1.ValueMember = "Fee"
End Sub
Let's simplify a bit:
Dim sql = "SELECT FeesTable.ID, CoNCAT(FeesTable.Particular, '-', FeesTable.Fee) as DisplayText
FROM
SubDepartmentsTable
inner join FeesTable on SubDepartmentsTable.MainDeptID = FeesTable.SubDepartmentID
WHERE SubDepartmentsTable.MainDeptID = #id"
Dim da As New SqlDataAdapter(sql, con)
da.SelectCommand.Parameters.AddWithValue("#id", Convert.ToInt32(TextDepartmentID.Text)) 'less worried about AWV with ints but read https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
Dim dt As New DataTable
da.Fill(dt)
'this part connects the data to the combo - it's the part you didn't show in your Q and what people are telling you is missing
yourCombo.DisplayMember = "DisplayText"
yourCombo.ValueMember = "ID"
yourCombo.DataSource = dt
This isn't intended to be a paste in fix for your problem; you've left out too much info from your question to know how to answer it exactly, so you're gonna have to modify this
Things you need to change:
The columns that are selected in the SQL - load one column you will show (I demonstrated how to combine two bits of info under one name of DisplayText) and one column for the backing value (ID)
The column that is filtered on in the where clause or the name of the text box TextDepartmentID - it seems odd to me that a Fee ID should be equal to a Department ID, so I've altered the SQL to retrieve the Fee details for a MainDepartmentID because I've assumed your textbox name is correct and that you intended to show the fees for a department via the subdepartments
Read the blog linked and perhaps choose adding a parameter in a different way
Change yourCombo to the name of your combobox
Change DisplayMember and ValueMember setting to match the names of the two columns your SQL query selects
You only need two columns if youre plumbing up a combo, but if you pass the datatable off somewhere you can add more
i had this sql query in vb.net where i have to use datagridview cell as parameter for the SELECT query.
here is the code:
Private Sub ClassSchedule()
Dim strConn As String = My.Settings.SLCBRegistrarDBConnectionString
Dim sqlCon As SqlConnection = New SqlConnection(strConn)
Try
sqlCon.Open()
Dim QUERY As String
QUERY = "SELECT CSchedClass.SCode as Code, ListofSubjects.[Course No.], ListofSubjects.[Descriptive Title], CSchedSubTD.TimeAndDay as Schedule, UtlyRoom.RoomName as Room, CSchedSubInstructor.NameInit as Instructor, CSchedSubDept.Dept, CSchedSubDept.Department " &
"FROM CSchedMAIN INNER JOIN CSchedClass ON CSchedMAIN.SubjCode = CSchedClass.id INNER JOIN ListofSubjects ON CSchedClass.Subj = ListofSubjects.SubjectID INNER JOIN CSchedSubTD ON CSchedMAIN.TDCode = CSchedSubTD.TDCode INNER JOIN UtlyRoom ON CSchedMAIN.RoomID = UtlyRoom.RoomID INNER JOIN CSchedSubInstructor ON CSchedMAIN.InstID = CSchedSubInstructor.EmpID INNER JOIN CSchedSubDept ON CSchedMAIN.Dept = CSchedSubDept.DeptID INNER JOIN SemesterList ON CSchedMAIN.SemID = SemesterList.SemID INNER JOIN SchoolYear ON CSchedMAIN.SYID = SchoolYear.[SY ID] INNER JOIN CSchedSubSect ON CSchedMAIN.Section = CSchedSubSect.id " &
"WHERE (CSchedSubSect.Section = '" & dgvSections.SelectedCells & "') AND (SchoolYear.[School Year] = '" & cmbSY.Text & "') AND (SemesterList.Description = '" & cmbSemester.Text & "')"
CMD = New SqlCommand(QUERY, sqlCon)
CMD.ExecuteNonQuery()
Adapter = New SqlDataAdapter(CMD)
DT = New DataTable()
Adapter.Fill(DT)
dgvSchedule.DataSource = DT
dgvSchedule.Columns(0).Width = 80
dgvSchedule.Columns(1).Width = 120
dgvSchedule.Columns(2).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
dgvSchedule.Columns(3).Width = 150
dgvSchedule.Columns(4).Width = 80
dgvSchedule.Columns(5).Width = 150
dgvSchedule.Columns(6).Visible = False
dgvSchedule.Columns(7).Visible = False
sqlCon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
The problem is the syntax for below is not correct:
WHERE (CSchedSubSect.Section = '" & dgvSections.SelectedCells & "')
The objective is when i click a specific cell in datagridview "dgvSections", the above query should execute and loads the data in datagridview "dgvSchedule".
Please help!
You need to parameterize you query.
By you using the SelectedCells property, I assume that you want to check for multiple values as well. If that is the case, then you also need to change your SQL statement from an equal sign operator to the IN operator which is the logical equivalent to using OR for multiple values. Otherwise, if you only want to check for a single value, then you need to change from using SelectedCells to CurrentCell.
Here is a quick example demonstrating what I'm suggesting:
'Declare the object that will bind the DataGridView
Dim dt As DataTable = New DataTable
'Declare the connection object
Dim con As SqlConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
'TODO: Change "My Connection String Here" with a valid connection string
con = New SqlConnection("My Connection String Here")
'Create a new instance of the command object
Using cmd As SqlCommand = New SqlCommand("SELECT
cschedclass.scode AS code,
listofsubjects.[Course No.],
listofsubjects.[Descriptive Title],
cschedsubtd.timeandday AS schedule,
utlyroom.roomname AS room,
cschedsubinstructor.nameinit AS instructor,
cschedsubdept.dept,
cschedsubdept.department
FROM cschedmain
INNER JOIN cschedclass
ON cschedmain.subjcode = cschedclass.id
INNER JOIN listofsubjects
ON cschedclass.subj = listofsubjects.subjectid
INNER JOIN cschedsubtd
ON cschedmain.tdcode = cschedsubtd.tdcode
INNER JOIN utlyroom
ON cschedmain.roomid = utlyroom.roomid
INNER JOIN cschedsubinstructor
ON cschedmain.instid = cschedsubinstructor.empid
INNER JOIN cschedsubdept
ON cschedmain.dept = cschedsubdept.deptid
INNER JOIN semesterlist
ON cschedmain.semid = semesterlist.semid
INNER JOIN schoolyear
ON cschedmain.syid = schoolyear.[SY ID]
INNER JOIN cschedsubsect
ON cschedmain.section = cschedsubsect.id
WHERE
cschedsubsect.section = #section AND
schoolyear.[School Year] = #year AND
semesterlist.description = #semester;", con)
'Parameterize the query
With cmd.Parameters
.AddWithValue("#section", dgvSections.CurrentCell.Value.ToString)
.AddWithValue("#year", cmbSY.Text)
.AddWithValue("#semester", cmbSemester.Text)
End With
'Create a DataAdapter to fill the underlying DataTable with data
Using adapter As SqlDataAdapter = New SqlDataAdapter(cmd)
'Open the connection
con.Open()
'Use the Fill method to complete the operation
adapter.Fill(dt)
'Close the connection
con.Close()
End Using
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
'Bind the table to the DataGridView
dgvSchedule.DataSource = dt
I got this little code where I connect to a db, select the data and write the data to a file.
...
sqlquery = ("select field1 as Asl, field2 as nCuen , field3 as nfac , "" as contr from [2016cl]")
Using connection As SqlConnection = New SqlConnection("server=" & srvSQL & ";database=" & bdSQL & ";uid=" & usrSQL & ";password=" & pswSQL & ";")
connection.Open()
Using comm As SqlCommand = New SqlCommand(sqlquery, connection)
Dim rs As SqlDataReader = comm.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(rs)
Call clCreateCSV.CreateCSVFile(dt, strFileNameDiario)
End Using
connection.Close()
End Using
.....
Public Shared Sub CreateCSVFile(dt As DataTable, strFilePath As String)
Dim sw As New StreamWriter(strFilePath, False, Encoding.UTF8)
Dim iColCount As Integer = dt.Columns.Count
For Each dr As DataRow In dt.Rows
For i As Integer = 0 To iColCount - 1
If Not Convert.IsDBNull(dr(i)) Then
sw.Write(dr(i).ToString())
End If
If i < iColCount - 1 Then
sw.Write(";")
End If
Next
sw.Write(sw.NewLine)
Next
sw.Close()
End Sub
I need to fill 4th value on the select ("" as contr) with field from another table which joins to another middle table.
field3 joins another table on GFac.Gfac2
the table Gfac joins the 3rd table on CCli.ccli1 --> this is the one I need on the query
Could just use inner join but, afaik it would only get the fields that validate the join.
how can i do this, writing ALL the data from [2016cl] and the field contr for each one of them if it exists?
Thanks in advance. If you need more info, just ask!
Use LEFT JOIN instead INNER JOIN.
For example:
SELECT * FROM TABLE1 LEFT JOIN TABLE2 ON ...
That query selects ALL rows from TABLE1. If a row in TABLE1 doesn't have a match record in TABLE2, then the TABLE2 fields contains NULL.
Hope that helps.
Please refer to this question: Visual Basic, filter on most occuring in Acces Databse
So after a long study I have made a form and figured out on how to show the query data in my datagridview1, I made it like this (as a Private sub)
Private Sub FilterNotations(ByVal Top As String)
Dim TopCat As String
TopCat = "TOP " & Top
con.Open()
Cmd = New OleDbCommand("SELECT " & TopCat & " categorie, COUNT(Id) AS n FROM notations GROUP BY categorie ORDER BY COUNT(Id) DESC", con)
Cmd.ExecuteNonQuery()
con.Close()
Using Cmd = New OleDbCommand("SELECT notations.* FROM notations INNER JOIN (SELECT " & TopCat & " categorie, COUNT(Id) AS n FROM notations GROUP BY categorie ORDER BY COUNT(Id) DESC) AS a ON notations.categorie = a.categorie", con)
con.Open()
Using Dad = New OleDbDataAdapter(Cmd)
Dst.Clear()
DataGridView1.DataSource = Dst.Tables()
Dad.Fill(Dst, "notations")
DataGridView1.DataSource = Dst.Tables(0)
End Using
End Using
con.Close()
End Sub
The next thing I need some help with is how can I, in addition to how I filter already use the date as in (01-07-16) to get the most occurring between date1 and date2. If some one could give me a gentle push in the right direction that would be kind.
UPDATE#1
I have investigated the clause WHERE and BETWEEN, from the information I could getter from the internet. I came up with this code:
Private Sub FilterNotations(ByVal Top As String)
Dim TopCat As String
TopCat = "TOP " & Top
con.Open()
Cmd = New OleDbCommand("SELECT " & TopCat & " categorie, COUNT(Id) AS n FROM notations WHERE creation_date BETWEEN #7/2/16# AND #7/5/16# GROUP BY categorie ORDER BY COUNT(Id) DESC", con)
Cmd.ExecuteNonQuery()
con.Close()
Using Cmd = New OleDbCommand("SELECT notations.* FROM notations INNER JOIN (SELECT " & TopCat & " categorie, COUNT(Id) AS n FROM notations WHERE creation_date BETWEEN #7/2/16# AND #7/5/16# GROUP BY categorie ORDER BY COUNT(Id) DESC) AS a ON notations.categorie = a.categorie", con)
con.Open()
Using Dad = New OleDbDataAdapter(Cmd)
Dst.Clear()
DataGridView1.DataSource = Dst.Tables()
Dad.Fill(Dst, "notations")
DataGridView1.DataSource = Dst.Tables(0)
End Using
End Using
con.Close()
End Sub
The problem is that in my datagrid it doesn't show the result I was hoping for.
The SELECT TOP x function works great but it doesn't filter the with date.
could someone please give me a hint.
Kind regards Jordy
As always I provide my own answer to my own question.
so I needed to put WHERE creation_date BETWEEN #7/2/16# AND #7/5/16# after AS a ON notations.categorie = a.categorie
Now it works as expected.
Thank you to jmcilhinney for providing the pieces I needed.