Get results from two tables - asp.net/SQL Server 2008R2 - asp.net

I have a search form with 2 fields(first name and last name) from one table (Just has person's information) and 4 (Incident number, date, place, created by) from the other (has one or more incidents for the person in the first table) linked through foreign key(nameID). I think the problem is what kind of join to use and how to use the WHERE clause.
Thanks.
More information:
#Tim - Isn't the user input into one or more fields the filter or it is the WHERE Clause? The user doesn't have to fill in all the fields. Thats where I am getting lost. The user is trying to find the incident to update it. Does this help?
Also I have to use "Like%LName%" in the Where clause to get all the names if they don't enter the entire name.
My query looks like this:
Protected Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim strSearch As String
strSearch = "SELECT tblPatron.LName, tblPatron.FName, tblIncident.CreatedBy, "
strSearch = strSearch + "tblIncident.Inci_ID, tblIncident.Inci_date, tblIncident.Inci_type, tblIncident.Library, "
strSearch = strSearch + "tblIncident.PatronName, tblIncident.Location "
strSearch = strSearch + "FROM tblPatron INNER JOIN tblIncident ON tblPatron.PatronID = tblIncident.PatronID "
strSearch = strSearch + "WHERE "
strSearch = strSearch + "(tblPatron.LName Like '%" + txtLName.Text.ToString() + "%') "
strSearch = strSearch + "AND (tblPatron.FNAME Like '%" + txtFName.Text.ToString() + "%')"
strSearch = strSearch + "AND (tblIncident.Inci_ID ='" + strInciNum.Text.ToString() + "')"
strSearch = strSearch + "AND (tblIncident.Inci_date = '" + txtInciDate.Text.ToString() + "')"
strSearch = strSearch + "AND (tblIncident.Inci_type = '" + ddInciCat.SelectedValue.Trim + "')"
strSearch = strSearch + "AND (tblIncident.Library = '" + ddLib.SelectedValue.Trim + "')"
SearchPDS.SelectCommand = strSearch
SearchPDS.DataBind()
GridSearchResults.DataBind()
GridSearchResults.Visible = True
End Sub

do this:
SELECT A.FirstName, A.LastName, B.IncidentNumber, B.Date, B.Place, B.CreatedBy
FROM Name A INNER JOIN Incident B
ON A.NameID = B.NameID

SELECT firstname, lastname, incidentnumber, date, place, createdby
FROM name n
INNER JOIN incident i ON n.nameID = i.nameID
WHERE firstname LIKE '%'+#firstname+'%'
AND lastname LIKE '%'+#lastname+'%'
Where #firstname and #lastname are parameters containing values from the search fields
In your string concatenation style, just add txtFName.Text.ToString() and txtLName.Text.ToString() into the string in place of those parameters.

I took the suggestion of logixologist. On the click event I added multiple if statements to check for the null value and then add build the query string. At the same time I made one of the dropdown to be a default value instead of "Select" and that would be my starting Where parameter. This works for me now. There might be a better way of writing the query, I am just beginner with asp.net
Thanks for all your replies. I love this forum.

What you need is dynamic sql. Basically you start by declaring a varchar(max)
DECLARE #Sql as varchar(max)
Then you will set it to the base SQL Statement:
SET #SQL = 'SELECT A.FirstName, A.LastName, B.IncidentNumber, B.Date, B.Place, B.CreatedBy
FROM Name A INNER JOIN Incident B
ON A.NameID = B.NameID where lastname IS NOT null ' -- PUT IN A WHERE CLAUSE THAT WILL ALWAYS BE TRUE
---Here is the concept in pseudo code
IF #lastname is not null
BEGIN
SET #SQL = #SQL + 'and lastname = '%' + #lastname + '%'
END
IF #FIRSTNAMEis not null
BEGIN
SET #SQL = #SQL + 'and FIRSTNAME = '%' + #FIRSTNAME+ '%'
END
At the end
EXEC (#SQL)
This will give you any option they put in.

Related

How to find value in a set in SQLite [duplicate]

In Mysql, FIND_IN_SET is used to find value in a set. I have tried FIND_IN_SET in SQLite, but it is not an SQL keyword. I have Googled, but I did not get an answer. If anybody knows, please tell me the alternative to FIND_IN_SET in SQLite.
If you need just a true / false value rather than index then you can use LIKE clause:
(',' || column_name || ',') LIKE '%,value,%'
we can write query like change into hibernate critearea
my old query
select * FROM game_detail WHERE content_id=176 and FIND_IN_SET(12,group_master_id)
New query
select *
FROM game_detail
WHERE content_id=176
and (group_master_id LIKE '%12,%'|| group_master_id LIKE '%,12,'|| group_master_id LIKE '%12')
This is my old query
String query = "SELECT a.content_id,a.content_name,a.image_name,a.image_path,a.rating,d.content_type_name"
+ "from content_master a, category_content_mapping b, "
+ "game_detail c, content_type_master d "
+ "where a.content_id=b.content_id "
+ "and c.content_id = a.content_id "
+ "and a.content_type_id = d.content_type_id "
+ "and b.category_id = '" + category_id + "' "
+ "and find_in_set('" + group_master_id + "',c.group_master_id) "
+ "and a.is_active='Y' and b.is_active = 'Y' and c.is_active = 'Y'"
+ "order by b.content_mapping_id DESC limit 0,3";
Criteria in hibernate use like alternate of find_in_set
Session session=new Configuration().configure().buildSessionFactory().openSession();
Criteria criteria=session.createCriteria(ContentMaster.class);
criteria.setFetchMode("CategoryContentMapping", FetchMode.JOIN);
criteria.setFetchMode("GameDetail", FetchMode.JOIN);
criteria.createAlias("categoryContentMappings","cat");
criteria.createAlias("contentTypeMaster", "ctm");
criteria.createAlias("gameDetails","game");
criteria.add(Restrictions.eq("cat.categoryMaster.categoryMasterId", 9));
criteria.add(Restrictions.disjunction()
.add(Restrictions.like("game.groupMasterId","%12,%"))
.add(Restrictions.like("game.groupMasterId","%,12,%"))
.add(Restrictions.like("game.groupMasterId","%12%")));
criteria.add(Restrictions.eq("isActive", "y"));
criteria.add(Restrictions.eq("cat.isActive", "y"));
criteria.add(Restrictions.eq("ctm.isActive", "y"));
criteria.addOrder(Order.desc("cat.contentMappingId"));

SQL Server Data type change from Numeric(7,3) to Varchar(20)

I have a field (dose_str) that needs to be changed from Numeric(7,3) to Varchar(20). I would like to know if there will be a need to change the query below (especially this portion SELECT (convert(varchar,cast(Prot_det.dose_str as float)) ) in the code of my application.
myCommand.CommandText = "
SELECT (convert(varchar,cast(Prot_det.dose_str as float)) + ' '
+ dose_unit + ' ' + dose_form_comment + ' ' + dose_mult) as Dose_str
from
Prot_det,
dosage_form
where
Protocol_num = '" & lblProtocol.Text & "' and
nsc_num = " & lstNSC.SelectedValue & " and
prot_det.dose_form = dosage_form.dose_form"
After changing the datatype of the column, you will be able to change this:
(convert(varchar,cast(Prot_det.dose_str as float))
to this:
(Prot_det.dose_str)
And I would recommend that you do.

Data from input box not inserting in to database

I made this form to insert information in database. I don't know where the error coming from. It's not inserting information from input fields to database.
Here's my code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim id, name, description, code, cat_industry, cat_theme, cat_occasion, cat_budget As String
id = product_id.Text
name = product_name.Text
description = product_description.Text
code = item_code.Text
cat_industry = industry.SelectedValue
cat_theme = theme.SelectedValue
cat_occasion = occasion.SelectedValue
cat_budget = budget.SelectedValue
Try
Dim str1 As String = "insert into product (ID, Product_Name, Product_Description, Item_Code, Industry, Theme, Occasion, Budget) values ('" + id + "', '" + name + "', '" + description + "', '" + code + "', '" + cat_industry + "', '" + cat_theme + "', '" + cat_occasion + "', '" + cat_budget + "')"
con.Open()
Dim cmd As New SqlCommand(str1, con)
cmd.ExecuteNonQuery()
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Your column names can't be referenced as Product Name and Product Description with a space - you will need to escape it as [Product Name], [Product Description] etc.
But please refrain from inserting data directly - instead you should be parameterizing your input variables. This has benefits from both a performance and security (Sql Injection) perspective.
Dim str1 As String = "insert into product (ID, [Product Name], [Product Description], Item_Code, etc) " _
" values (#id, #name, #description, #code, etc)"
con.Open()
Dim cmd As New SqlCommand(str1, con)
cmd.Parameters.AddWithValue("#id", id )
cmd.Parameters.AddWithValue("#name", name )
... etc
cmd.ExecuteNonQuery()

Search command using session variable asp.net

I have a name stored in a session variable called "name".
I have written the statement:
da = new SqlDataAdapter("Select empID from emp where empFirstName=' "+
Session["name"].ToString() + " '", connstring);
da.Fill(ds);
I have verified that the session variable is not empty. Yet i am not able to fetch the empID of the record that exists in the table. Is this statement correct?
You have spaces at the beginning and end of the string variable in SQL statement.
Try this, it should work:
da = new SqlDataAdapter("Select empID from emp where empFirstName='"+
Session["name"].ToString() + "'", connstring);
The problem was with the spaces over here:
' " + Session["name"].ToString() + " '"
^ ^
| |
that is why the values are suffixed and prefixed by a blank space.
You should try:
da = new SqlDataAdapter (
"Select empID from emp where empFirstName='" + Session["name"].ToString() + "'",
connstring);
da.Fill(ds);

error in submit button

I have an error in the execution of my code. It says "Syntax error in INSERT INTO statement". This is my code:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click GridView1.Visible = True
Dim myConn As OleDbConnection
Dim sqlString, takenby, dest, client, car As String
Dim recordno As Integer
Dim dte, exptime As String
recordno = TextBox4.Text
dte = TextBox1.Text
car = ComboBox1.SelectedValue.ToString()
takenby = ComboBox2.SelectedValue.ToString
dest = ComboBox3.SelectedValue.ToString
client = TextBox2.Text
exptime = TextBox3.Text
myConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\student\WebSite3\App_Data\Database.mdb;Persist Security Info=False;")
myConn.Open()
sqlString = "INSERT INTO DETAILED GISTEC CARS(Record No, Date, Car, Taken By, Destination, Client, Expected Time to Return)VALUES(?recordno, ?dte, ?car, ?takenby, ?dest, ?client, ?exptime);"
Dim cmd = New OleDbCommand(sqlString, myConn)
cmd.ExecuteNonQuery()
myConn.Close()
End Sub
You should change your query to use question mark placeholders and then add paramters to prevent (amongst other things) sql injection issues.
You also need to add square brackets to your column names if they have spaces in them:
sqlString = "INSERT INTO [DETAILED GISTEC CARS] ([Record No], [Date], [Car], [Taken By], [Destination], [Client], [Expected Time to Return]) VALUES (?, ?, ?, ?, ?, ?, ?);"
Dim cmd = New OleDbCommand(sqlString, myConn)
cmd.Parameters.Add(New OleDbParameter("Record No", recordno))
cmd.Parameters.Add(New OleDbParameter("Date", dte))
'etc
'etc
cmd.ExecuteNonQuery()
See this page about OleDbParameters for more information.
Try to execute query directly in Access until it works.
From here it looks like
You have no spaces around VALUES
Your table name contain spaces so better use [] to surround table name
Same with some column names.
Not sure of ?recordno syntax in vb so better use + operator
sqlString = "INSERT INTO [DETAILED GISTEC CARS]([Record No], [Date], [Car], [Taken By], [Destination], [Client], [Expected Time to Return]) VALUES (" + recordno + ", " + dte + ", " + car +", " + takenby, " + dest + ", " + client + ", " + exptime + ");"
An alternative to cad's concatenation method would be to use curly brace array placeholders. Something like this should do it:
sqlString = String.Format("INSERT INTO [DETAILED GISTEC CARS] ([Record No], [Date], [Car], [Taken By], [Destination], [Client], [Expected Time to Return]) VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6});", recordno, dte, car, takenby, dest, client, exptime)
You should also put single quotes around non-numeric values, escape any user entered single quotes, and call the Access CDATE function for Date/Time columns. So, assuming dte is user entered data and exptime is a Date\Time column, those two variables might be set like this:
dte = "'" + TextBox1.Text.Replace("'", "''") + "'"
exptime = "CDATE('" + TextBox3.Text + "')"
and so on and so forth...

Resources