Join Query in string format - asp.net

Hi i'm trying to join tables together when loading my session variable Below is my code
Dim cmdstring As String = "SELECT * FROM Users.Location_Code = Location.Location_Code =
Medical_Equipment.Location_Code WHERE Staff_No = #StaffNo"
I am attempting a 3 table join this data will then be presented on a grid view. Is it possible for a join to be made here in this string?

Yes it is possible. But you need to have proper SQL JOIN syntax. Your current SQL query doesn't make sense. It should look about like this (I assume that Staff_No is a column in Users table) :
Dim cmdstring As String = _
"SELECT * FROM Users u " & _
"INNER JOIN Location l on l.Location_Code = u.Location_Code " & _
"INNER JOIN Medical_Equipment m on m.Location_Code = u.Location.Location_Code " & _
"WHERE u.Staff_No = #StaffNo"

Related

use operation logic inside SQL Query?

I have a Query string inside Employees Page that read URL Parameter
to get Companies employees from DataBase if parameter is ALL the page should display ALL Employees but if CompID Equal Specific ID it will Get only Employees for this Company to do that i am using two queries but i am sure that i can use only one query to get the same result
my Query String Parameter is :
String CompID = HttpUtility.UrlDecode(Request.QueryString["CompID"]);
The SQL Query to display ALL Employee is :
Query1 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
" TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
"TbEmp.address, TbComp.compName From TbEmp" +
" INNER JOIN TbComp on TbComp.compID = TbEmp.compID ORDER BY TbComp.compID"
The SQL Query to Display Employees for specific companie is :
Query2 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
" TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
"TbEmp.address, TbComp.compName From TbEmp" +
" INNER JOIN TbComp on TbComp.compID = TbEmp.compID WHERE TbEmp.compID = #CompID ORDER BY TbComp.compID DESC"
Can someone help me to merge those two queries in one query ?
The is a simple or-and case. Assuming your #CompID is numeric and you can send a zero to indicate the 'All' search...
INNER JOIN TbComp on TbComp.compID = TbEmp.compID
WHERE (#CompID = 0) or (#CompID <> 0 and TbEmp.compID = #CompID)
ORDER BY TbComp.compID DESC"
Although I would not suggest using queries to write your logic in asp.net (use stored procedures with parameters instead).
You can do this :
Solution 1 :
string Query1 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
" TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
"TbEmp.address, TbComp.compName From TbEmp" +
" INNER JOIN TbComp on TbComp.compID = TbEmp.compID " ;
String CompID = HttpUtility.UrlDecode(Request.QueryString["CompID"]);
if( CompID<>"")
{
Query1 += " WHERE TbEmp.compID = " + CompID //Beware : Chance of injection
}
Query1 +=" ORDER BY TbComp.compID";
Solution 2 : Assuming #CompID will be passed null if it is not there.
Query2 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
" TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
"TbEmp.address, TbComp.compName From TbEmp" +
" INNER JOIN TbComp on TbComp.compID = TbEmp.compID WHERE
TbEmp.compID = Isnull(#CompID, TbEmp.compID) ORDER BY TbComp.compID DESC"

Microsoft SQL search table for entry

I'm working on a inventory system for a micro brewery and I have a question about adding customers to a database. I want to add customers only if they don't already have an entry. What command could I use to check for that?
Here's my code so far (ASP.NET)
con.ConnectionString = "****"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Customer(Name, Address) VALUES('" & Namea & "','" & Addressa & "')"
cmd.ExecuteNonQuery()
cmd.CommandText = "SELECT Customer_ID FROM Customer WHERE (Name = '" & Namea & "')"
custID = cmd.ExecuteScalar
cmd.CommandText = "SELECT Order_Details_ID FROM OrderDetails WHERE Finished_Inventory_ID=" & OrdersInt & ""
ordrID = cmd.ExecuteScalar
cmd.CommandText = "INSERT INTO Orders(Customer_ID, Order_Details) VALUES(" & Integer.Parse(custID) & "," & Integer.Parse(ordrID) & ")"
cmd.ExecuteNonQuery()
con.Close()
Is there a Boolean command that will return true if there's already a entry with the specific Namea. I don't want multiple entries with the same customer name.
There are a number of ways to prevent duplicate entries. You can check first:
select count(*) records
from etc
Then look at the value of records. If it's 0, do the insert. Or you can use a subquery.
insert into table
(field1, field2, etc)
select value1, value2, etc
where (select count(*) etc ) = 0
or like this:
insert into table
(field1, field2, etc)
select value1, value2, etc
where not exists (select 1 from table etc)
In all cases, the etc part is a search for records you don't want to duplicate.

My code is producing incorrect result. Can anyone please tell me what I am doing wrong?

My apologies up front for the long thread.
I am very flabbergasted as to why this code is not working correctly.
Please have a look.
On markup,
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="cancelBtn" style="width:105px;padding:5px;margin:5px;" runat="server" CommandName="delete" OnDataBinding="btnDelete_DataBinding" OnClientClick='return confirm("Are you sure you want to delete this entry?");' Text="Cancel Training" />
</ItemTemplate>
</asp:TemplateField>
Then I have a function called getDateDifference() As Boolean with code below:
Private Function getDateDifference() As Boolean
Dim username = Session("Username")
Dim myConnectionString As [String] = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim myConnection As New SqlConnection(myConnectionString)
myConnection.Open()
Dim cmd1 As New SqlCommand("select DateDiff(dd,GetDate(),d.trainingDates) as DaysCount " & _
"from tblTrainings t Inner Join tblCourses c on t.courseId = c.courseId " & _
"Inner Join tblLocations l on t.locationId = l.LocationId " & _
"Inner Join tblTrainingDates d on t.dateid=d.dateid " & _
"Inner Join tblCourseInstructor ic on c.courseId = ic.CourseId " & _
"Inner Join tblInstructors i on ic.instructorId = i.instructorId " & _
"Inner Join tblLogin lg on t.username = lg.username where lg.username = #username", myConnection)
cmd1.Parameters.AddWithValue("#username", username)
Dim dr1 As SqlDataReader = cmd1.ExecuteReader()
If dr1.Read() Then
Dim DaysCount As Integer = dr1("DaysCount")
Response.Write(DaysCount)
If DaysCount >= 2 Then
Return True
Else
Return False
End If
End If
Return False
End Function
The function is invoked below:
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim btn As Button = DirectCast(e.Row.FindControl("cancelBtn"), Button)
btn.Enabled = Not getDateDifference()
End If
End Sub
All we trying do to is compare trainingdates with current date.
If current date is within 24 hours (or 2 days) of training date, a user who has already signed up for a class, cannot cancel that class.
The user can cancel if current date is more than 2 days before training date.
To test, I have 2 trainings scheduled on my account.
One training date is 6/22/2013
The other training date is 6/29/2013.
When I run the query above, I get 1, and 8 days respectively.
This is correct because today's date is 6/21/2013 which is there is one day left before first training date of 6/22/2013 and 8 days left
before the second training date of 6/29/2013.
This means that on my app (please see screenshot), I expect to see one button disabled and the other enabled.
![enter image description here][1]
As you can see from screenshot, this is not happening. Both are either getting enabled or disabled no matter what the training date is.
When I try to debug DaysCount with response.write (DaysCount), it shows 11.
Not sure how this is happening. It has been at least 3 days since I have been struggling with this.
DB is sql server 2005. However production db is 2008.
Thanks in advance for your assistance.
I'm not sure what is happening here, but to try and debug it I would just return d.trainingDates from your database query instead of doing the DateDiff, and then do this to validate it:
If dr1.Read() Then
Dim trngDate As Date = dr1("trainingDates")
Response.Write(trngDate.ToString)
If (trngDate - DateTime.Now).TotalDays >= 2 Then
Return True
Else
Return False
End If
End If
EDIT
But - why not just compare the dates in the RowDataBound event.
There is no need to perform another query, the date your are comparing is in the row you are binding
Something like this (untested) code:
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim dateValue As Date = Date.Parse(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Dates")))
Dim btn As Button = DirectCast(e.Row.FindControl("cancelBtn"), Button)
btn.Enabled = (dateValue - DateTime.Now).TotalDays >= 2
End If
End Sub
I know you accepted #Matt Wilko's answer, but just to answer the specific problem you're facing:-
The problem is that your query returns all tblTraining records for the user. There is no condition in the where clause to determine which tblTraining record is the current active one.
Response.Write(DaysCount) did not produce 11, but rather produced 1 and 1, which is the difference between 6/22/2013 and 6/21/2013. You had 2 rows, so each digit must have been for a different row, and both rows seems to be getting the same date difference.
You will probably need to declare Private Function getDateDifference(courseId as Integer) As Boolean or something similar, so that you can pass the courseId to the function and use it in your SQL statement to identify the specific training program that you want. Probably your SQL statement will look something like
Dim cmd1 As New SqlCommand(_
"select DateDiff(dd,GetDate(),d.trainingDates) as DaysCount " & _
"from tblTrainings t Inner Join tblCourses c on t.courseId = c.courseId " & _
"Inner Join tblLocations l on t.locationId = l.LocationId " & _
"Inner Join tblTrainingDates d on t.dateid=d.dateid " & _
"Inner Join tblCourseInstructor ic on c.courseId = ic.CourseId " & _
"Inner Join tblInstructors i on ic.instructorId = i.instructorId " & _
"Inner Join tblLogin lg on t.username = lg.username " & _
"where lg.username = #username and " & _
"t.courseId = #courseId", myConnection)
cmd1.Parameters.AddWithValue("#courseId", courseId)
As to where you can get your courseId, you can probably use the approach #Matt Wilko used. But then again, his method would have avoided this whole issue altogether.

reading table using reader ASP.NET and VB

I have a view patients page and it shows all patients and there's a link next to each patient which takes you to another page where the user can update the patient's information using textboxes and dropdownlists .. i used query string choose a certain patient and reader command to read from the database ..
The problem is the reader isn't accessing the table at all .. can you help me please?
pid = Request.QueryString("Pateint_ID")
Dim tempQuery As String = "SELECT P.first_name, P.sec_name, P.third_name, P.last_name, P.Gender, PATA.ApplicationStatus," & _
"P.DoB, P.birthplace, P.Nationality, P.patient_ID, P.issue_date, P.issue_place, P.city, " & _
"P.Area,h.Name , h.DialysisCetner, p.Mobile_No, p.Work_phone, p.PhoneNo, p.Zipcode, p.POBox, p.problemWithDialysis" & _
"FROM Association AS A INNER JOIN PatientApplyToAssociation AS PATA INNER JOIN" & _
"patient AS P ON PATA.patient_ID = P.patient_ID ON A.Association_ID = PATA.Association_ID INNER JOIN " & _
"hospital AS H INNER JOIN TreatmentSession AS ts ON ts.Name = H.Name ON p.patient_ID = ts.patient_ID LEFT OUTER JOIN Family AS F INNER JOIN" & _
"Gardian AS G ON F.family_ID = G.GID INNER JOIN Relates AS R ON F.family_ID = R.family_ID ON P.patient_ID = R.patient_ID" & _
"WHERE (P.patient_ID = pid )"
Dim query As String = String.Format(tempQuery, pid)
Dim comm As New SqlCommand(query, con)
Dim reader As SqlDataReader
Try
con.Open()
reader = comm.ExecuteReader()
If reader.Read() Then
txtFirstName.Text = reader("first_name").ToString()
txtFatherName.Text = reader("sec_name").ToString()
txtGrandName.Text = reader("third_name").ToString()
txtFamilyName.Text = reader("last_name").ToString()
rblGender.SelectedValue = reader("Gender").ToString()
txtBirthdate.Text = reader("DoB").ToString()
ddlBirthPlace.SelectedValue = reader("birthplace").ToString()
txtNationality.Text = reader("Nationality").ToString()
txtIDCard.Text = reader("patient_ID").ToString()
ddlIssuePlace.SelectedValue = reader("issue_place").ToString()
txtIssuedate.Text = reader("issue_date").ToString()
ddlAddressCity.SelectedValue = reader("city").ToString()
ddlAddressRegion.SelectedValue = reader("area").ToString()
End If
Catch ex As Exception
MsgBox("somthing's wrong")
Finally
con.Close()
End Try
Based on your last comment, im guessing its an SQL problem. I would first take your query and run it in query analyzer to make sure its valid.
Your query looks incorrect.
After cleaning up your query so it was legible I noticed this
SELECT P.first_name, P.sec_name, P.third_name, P.last_name, P.Gender, PATA.ApplicationStatus,
P.DoB, P.birthplace, P.Nationality, P.patient_ID, P.issue_date, P.issue_place, P.city,
P.Area,h.Name , h.DialysisCetner, p.Mobile_No, p.Work_phone, p.PhoneNo, p.Zipcode, p.POBox, p.problemWithDialysis
FROM Association AS A INNER JOIN PatientApplyToAssociation AS PATA
INNER JOIN patient AS P ON PATA.patient_ID = P.patient_ID ON A.Association_ID = PATA.Association_ID
INNER JOIN hospital AS H
INNER JOIN TreatmentSession AS ts ON ts.Name = H.Name ON p.patient_ID = ts.patient_ID
LEFT OUTER JOIN Family AS F
INNER JOIN Gardian AS G ON F.family_ID = G.GID INNER JOIN Relates AS R ON F.family_ID = R.family_ID ON P.patient_ID = R.patient_ID
WHERE (P.patient_ID = pid )
Notice 2 of your joins dont have ON clauses? Not to mention you have 3 joins that have multiple ON clauses?

SQLite data dictionary tables and columns

Can you tell us the names of all tables and table columns in the SQLite data dictionary?
Update:
I was using this information for a Basic4Android app I'm developing.
Here is the actual segment of coding I used:
' Create the PeopleToVisit table which holds lookup data about each visit.
'-------------------------------------------------------------------------
If SQL.ExecQuerySingleResult( _
"SELECT count(name) FROM sqlite_master WHERE type='table' AND name='PeopleToVisit'") _
= 0 Then
ToastMessageShow("Creating the People to Visit table.", False)
' Create it now since it doesn't yet exist.
'------------------------------------------
SQL.ExecNonQuery("CREATE TABLE PeopleToVisit (" & _
"Id INTEGER PRIMARY KEY, " & _
"FirstName TEXT, " & _
"LastName TEXT, " & _
"Address1 TEXT, " & _
"Address2 TEXT, " & _
"City TEXT, " & _
"State TEXT, " & _
"Zip TEXT " & _
")")
End If
' New table columns for Version 1.2
'----------------------------------
' Coding for when new data columns need to be added to the database table.
'-------------------------------------------------------------------------
strCreateTableStatement = _
SQL.ExecQuerySingleResult("SELECT sql " & _
"FROM sqlite_master " & _
"WHERE Type = 'table' AND name = 'PeopleToVisit'")
' Check if the new columns are in the table.
'-------------------------------------------
If strCreateTableStatement.IndexOf("PrimaryPhone TEXT") = -1 Then
' We need to add the new columns to the table.
'---------------------------------------------
SQL.ExecNonQuery("ALTER TABLE PeopleToVisit ADD COLUMN PrimaryPhone TEXT")
SQL.ExecNonQuery("ALTER TABLE PeopleToVisit ADD COLUMN SecondaryPhone TEXT")
SQL.ExecNonQuery("ALTER TABLE PeopleToVisit ADD COLUMN Email TEXT")
SQL.ExecNonQuery("ALTER TABLE PeopleToVisit ADD COLUMN LastVisitNote TEXT")
End If
To list all tables in a database
SELECT name FROM sqlite_master WHERE type='table'
To list all columns in a table
pragma table_info(table_name)

Resources