use operation logic inside SQL Query? - asp.net

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"

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"));

Stored Procedures and asp.net programmability; variable or SQL

Trying to display a users Lastname, Firstname --- Website
And I need to insert a comma and space after Lastname to a GridView.
I am trying to add a CASE statement in SQL and having trouble figuring it out.
Perhaps I need to use #parameter (scalar variable?) to abstract the
memory read from CASE statement; or my syntax is wrong and I just don't
understand.
SELECT
CASE
WHEN IsNull(people_Table.firstName, '') = ''
THEN CONCAT(people_Table.lastName, ', ', people_Table.firstName)
ELSE people_Table.lastName
END as fullName,
people_Table.website
FROM
people_Table
INNER JOIN
membership_Table on people_Table.ID = membership_Table.personID
WHERE
rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY
people_Table.lastName
Getting SQL Server error:
Msg 208, Level 16, State 1, Line 1
Invalid object name 'people_Table'.
Otherwise I suppose I should use an asp databoundevent in the template.
What is better for performance and security?
SELECT ISNULL(people_Table.lastName + ', ', '')
+ ISNULL(people_Table.firstName , '') as fullName
, people_Table.website
FROM people_Table INNER JOIN membership_Table on people_Table.ID =
membership_Table.personID
WHERE rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY people_Table.lastName
OR
SELECT COALESCE(people_Table.lastName + ', ', '')
+ COALESCE(people_Table.firstName , '') as fullName
, people_Table.website
FROM people_Table INNER JOIN membership_Table on people_Table.ID =
membership_Table.personID
WHERE rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY people_Table.lastName

Join Query in string format

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"

Run a Stored Procedure multiple times dynamically

I have created a stored procedure that calculates from some table and retrieve a new dataset back:
" DECLARE #maxVal int " +
" Set #maxVal = (SELECT ID FROM TableCustomers " +
" WHERE Service_ID = #Service_ID) " +
" execute SP_CaculateData #maxVal ";
Now the TableCustomers also have a column called CustomerName and each CustmerName can have multiple Service_ID's.
How can I run my stored procedure multiple times, all depends on how many services each CustomerName has. Something like:
execute SP_CaculateData #maxVal
execute SP_CaculateData #maxVal
execute SP_CaculateData #maxVal
execute SP_CaculateData #maxVal
I have been reading something about cursors, but if anyone can give me a hand hear I would appreciate that.
One option is to use a while loop to iterate through the customers and service ids:
declare
#maxVal int
,#customerName varchar(200)
,#serviceID int
select #customerName = MIN(CustomerName)
from TableCustomers t
while(select COUNT(1)
from TableCustomers t
where t.CustomerName >= #customerName) > 0
begin
--here we are dealing w/ a specific customer
--loop through the serviceIDs
select #serviceID = MIN(Service_ID)
from TableCustomers t
where t.CustomerName = #customerName
while(select COUNT(1)
from TableCustomers t
where t.CustomerName = #customerName
and t.Service_ID >= #serviceID) > 0
begin
select #maxVal = MAX(Id)
from TableCustomers t
where t.Service_ID = #serviceID
execute SP_CalculateData #maxVal
select #serviceID = MIN(Service_ID)
from TableCustomers t
where t.CustomerName = #customerName
and t.Service_ID > #serviceID
end
select #customerName = MIN(CustomerName)
from TableCustomers t
where t.CustomerName > #customerName
end
I can't say whether or not this is a solution that will perform better than a cursor, but it should get the job done.

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

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.

Resources