I'm trying to run a query on an Access DB, I'm used to SQL queries but this doesn't seem to be working the same way. Here's my query:
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "SELECT RecordID, TimeStamp, EmployeeName, AreaDescription FROM LoginRecords r, Employees e, Areas a WHERE((e.EmployeeID = r.EmployeeID) && (a.AreaID =r.AreaID) && (TimeStamp > startDate AND < endDate)) ORDER BY TimeStamp;"
I can't seem to get this to run but technically from a SQL standpoint this should be a good query. The tables are LoginRecords, Employees, Areas. I can load the tables if that would be helpful. I appreciate any feedback as to why this won't work in Access. And startDate and endDate are variables from user input boxes.
Try this one,
This is SQL-92
SELECT RecordID,
TimeStamp,
EmployeeName,
AreaDescription
FROM LoginRecords r
INNER JOIN Employees e
ON e.EmployeeID = r.EmployeeID
INNER JOIN Areas a
ON a.AreaID = r.AreaID
WHERE TimeStamp > startDate AND
TimeStamp < endDate
ORDER BY TimeStamp;
Use SQL-92 format rather SQL-89 format because SQL-89 (aside from old style) is prone to going CROSS JOIN if not handled correctly.
and this is SQL-89
SELECT RecordID,
TimeStamp,
EmployeeName,
AreaDescription
FROM LoginRecords r, Employees e, Areas a
WHERE (e.EmployeeID = r.EmployeeID) AND
(a.AreaID = r.AreaID) AND
(TimeStamp > #startDate AND
TimeStamp < #endDate)
ORDER BY TimeStamp;
MSACCESS: INNER JOIN, OUTER JOIN (LEFT and RIGHT)
Related
I have this query and i get results when i execute it on Sql studio:
select TeamName, count(*)
from NetHoz_Decision
inner join NetHoz_Case on NetHoz_Decision.CaseDisplayIdentifier = NetHoz_Case.CaseDisplayIdentifier
inner join maintik on MainTik.Counter = NetHoz_Case.TikCounter
inner join Teams on MainTik.TeamCounter = Teams.Counter
where NetHoz_Decision.DecisionStatusChangeDate between '2015-07-23' and '2015-07-28'
group by TeamName
But when i execute it on C# SqlCommand I don't get any result.
The dataSet is empty and i don't get any error.
I thought the problem might be on date.
Am i converting it right?
String date1 = String.Format("{0:yyyy-MM-dd}", dateTimePicker1.Value);
String date2 = String.Format("{0:yyyy-MM-dd}", dateTimePicker2.Value.AddDays(1));
Using SqlCommand and type-safe parameters
const string query = "
select TeamName, count(*)
from NetHoz_Decision
inner join NetHoz_Case on NetHoz_Decision.CaseDisplayIdentifier = NetHoz_Case.CaseDisplayIdentifier
inner join maintik on MainTik.Counter = NetHoz_Case.TikCounter
inner join Teams on MainTik.TeamCounter = Teams.Counter
where NetHoz_Decision.DecisionStatusChangeDate between #from and #to
group by TeamName
";
SqlCommand command = new SqlCommand(query);
command.Parameters.AddWithValue("#from", dateTimePicker1.Value);
command.Parameters.AddWithValue("#to", dateTimePicker2.Value.AddDays(1));
DateTime startDate = DateTime.ParseExact(txtstart.Text, "MM/dd/yyyy", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MM/dd/yyyy", null);
string n1 = DropDownList2.SelectedItem.Text;
if (DropDownList1.SelectedItem.Text == "Membership")// here you can add selectedindex as well
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ToString());
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select * from Membership_det where updateDate between #Start and #End and FID ="+n1+"", con);
adapter.SelectCommand.Parameters.Add("#Start", SqlDbType.Date).Value = startDate;
adapter.SelectCommand.Parameters.Add("#End", SqlDbType.Date).Value = endDate;
}
……..
……..
Above is a part of a code to display the data in the grid view.I am displaying * from Membership_det and also need to display faculty name from other table…how to add the query with the above query..displaying * from membership _det table and faculty name from other table
FID MembNo MembType Validity Remarks UpdateDate
100 23 basn 6 dgag 9/5/2013 12:00:00 AM
200 566 basn 6 adhu 9/6/2013 12:00:00 AM
In this table i need to add Faculty name..it should be fetched from other table..
You can JOIN tables as below. Change the Relationship and the column names based on your tables. it is better if you can use parameter for FID as well
SELECT m.*, f.Name
FROM Membership_det m
INNER JOIN faculty f
ON m.FID = f.FID
WHERE m.updateDate between #Start and #End and m.FID =#FID ;
You can join Memberhip_det table with the other table to retrieve faculty_name. But these two tables should have a common connecting field or primary and foreign keys.
Also try using stored procedures rather than inline queries
Try to use union for your two sql select statements
UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
Make foreign key relation ship to FID column on faculty table and change your query as follows
select Membership_det.MembNo, Membership_det.MembType,Membership_det.Validity,Membership_det.Remarks,Membership_det.UpdateDate,faculty.facultyname FROM Membership_det INNER JOIN faculty ON Membership_det.FID = faculty.FID
WHERE Membership_det.updateDate between #Start and #End and Membership_det.FID =#FID ;
I am trying to write an SQL (Server) query which will return all events on a current day, and for all events where the column recurring= 1, I want it to return this event on the day it is being held and for the subsequent 52 weeks following the event.
My tables are structured as followed :
Event
{
event_id (PK)
title,
description,
event_start DATETIME,
event_end DATETIME,
group_id,
recurring
}
Users
{
UserID (PK)
Username
}
Groups
{
GroupID (PK)
GroupName
}
Membership
{
UserID (FK)
GroupID (FK)
}
The code I have thus far is as follows :
var db = Database.Open("mPlan");
string username = HttpContext.Current.Request.Cookies.Get("mpUsername").Value;
var listOfGroups = db.Query("SELECT GroupID FROM Membership WHERE UserID = (SELECT UserID from Users WHERE Username = #0 )", username);
foreach(var groupID in listOfGroups)
{
int newGroupID = groupID.GroupID;
var result = db.Query(
#"SELECT e.event_id, e.title, e.description, e.event_start, e.event_end, e.group_id, e.recurring
FROM event e
JOIN Membership m ON m.GroupID = e.group_id
WHERE e.recurring = 0
AND m.GroupID = #0
AND e.event_start >= #1
AND e.event_end <= #2
UNION ALL
SELECT e.event_id, e.title, e.description, DATEADD(week, w.weeks, e.event_start), DATEADD(week, w.weeks, e.event_end), e.group_id, e.recurring
FROM event e
JOIN Membership m ON m.GroupID = e.group_id
CROSS JOIN
( SELECT row_number() OVER (ORDER BY Object_ID) AS weeks
FROM SYS.OBJECTS
) AS w
WHERE e.recurring = 1
AND m.GroupID = #3
AND DATEADD(WEEK, w.Weeks, e.event_start) >= #4
AND DATEADD(WEEK, w.Weeks, e.event_end) <= #5", newGroupID, start, end, newGroupID, start, end
);
This results in when one queries for the date of the event stored in the database, this event and 52 weeks of events are returned. When one queries for the event the week after this one, nothing is returned.
The simplest solution would be to alter the following 2 lines
AND e.event_start >= #4
AND e.event_end <= #5"
to
AND DATEADD(WEEK, w.Weeks, e.event_start) >= #4
AND DATEADD(WEEK, w.Weeks, e.event_end) <= #5"
However, I'd advise putting all this SQL into a stored procedure, SQL-Server will cache the execution plans and it will result in (slightly) better performance.
CREATE PROCEDURE dbo.GetEvents #UserName VARCHAR(50), #StartDate DATETIME, #EndDate DATETIME
AS
BEGIN
-- DEFINE A CTE TO GET ALL GROUPS ASSOCIATED WITH THE CURRENT USER
;WITH Groups AS
( SELECT GroupID
FROM Membership m
INNER JOIN Users u
ON m.UserID = u.UserID
WHERE Username = #UserName
GROUP BY GroupID
),
-- DEFINE A CTE TO GET ALL EVENTS FOR THE GROUPS DEFINED ABOVE
AllEvents AS
( SELECT e.*
FROM event e
INNER JOIN Groups m
ON m.GroupID = e.group_id
UNION ALL
SELECT e.event_id, e.title, e.description, DATEADD(WEEK, w.weeks, e.event_start), DATEADD(WEEK, w.weeks, e.event_end), e.group_id, e.recurring
FROM event e
INNER JOIN Groups m
ON m.GroupID = e.group_id
CROSS JOIN
( SELECT ROW_NUMBER() OVER (ORDER BY Object_ID) AS weeks
FROM SYS.OBJECTS
) AS w
WHERE e.recurring = 1
)
-- GET ALL EVENTS WHERE THE EVENTS FALL IN THE PERIOD DEFINED
SELECT *
FROM AllEvents
WHERE Event_Start >= #StartDate
AND Event_End <= #EndDate
END
Then you can call this with
var result = db.Query("EXEC dbo.GetEvents #0, #1, #2", username, start, end);
This elimates the need to iterate over groups in your code behind. If this is actually a requirement then you could modify the stored procedure to take #GroupID as a parameter, and change the select statements/where clauses as necessary.
I have assumed knowledge of Common Table Expressions. They are not required to make the query work, they just make things slightly more legible in my opinion. I can rewrite this without them if required.
I would check my parameters one at a time against some trivial SQL, just to rule them out as possible culprits. Something like this:
var result = db.Query("select r=cast(#0 as varchar(80))",username);
var result = db.Query("select r=cast(#0 as int)",newGroupID);
var result = db.Query("select r=cast(#0 as datetime)",start);
var result = db.Query("select r=cast(#0 as datetime)",end);
I have a member table with columns
member_id
member_lastname
member_firstname
i have another table visits with columns
visit_id
member_id
visit_date
i have got the mysql query like this
string sql = #"SELECT COUNT('x') AS numVisits, member_firstname as firstname, member_lastname as lastname, members.member_id
FROM visits, members
WHERE visits.member_id = members.member_id
AND visit_Date BETWEEN #startdate AND #enddate
GROUP BY member_firstname, member_lastname, members.member_id
ORDER BY COUNT('x') DESC";
How can i convert this query into linq to entities
my entity name is trasitdbcontext
would any one pls give any idea about this ..
Many thanks...
from v in visits
join m in members on v.member_id equals m.member_id
where v.visit_Date >= startDate && v.visit_Date <= endDate
group m by new { m.member_firstname, m.member_lastname, m.member_id } into g
orderby g.Count()
select new
{
count = g.Count(),
member_firstname = g.Key.member_firstname,
member_lastname = = g.Key.member_lastname,
member_id = = g.Key.member_id,
}
I have three tables, Entity, Period and Result. There is a 1:1 mapping between Entity and Period and a 1:Many between Period and Result.
This is the linq query:
int id = 100;
DateTime start = DateTime.Now;
from p in db.Periods
where p.Entity.ObjectId == id && p.Start == start
select new { Period = p, Results = p.Results })
This is relevant parts of the generated SQL:
SELECT [t0].[EntityId], [t2].[PeriodId], [t2].[Value], (
SELECT COUNT(*)
FROM [dbo].[Result] AS [t3]
WHERE [t3].[PeriodId] = [t0].[Id]
) AS [value2]
FROM [dbo].[Period] AS [t0]
INNER JOIN [dbo].[Entity] AS [t1] ON [t1].[Id] = [t0].[EntityId]
LEFT OUTER JOIN [dbo].[Result] AS [t2] ON [t2].[PeriodId] = [t0].[Id]
WHERE ([t1].[ObjectId] = 100) AND ([t0].[Start] = '2010-02-01 00:00:00')
Where is the SELECT Count(*) coming from and how can I get rid of it? I don't need a count of the "Results" for each "Period" and it slows the query down by an order of magnitude.
Consider using the Context.LoadOptions and specifying for Period to LoadWith(p => p.Results) to eager load the period with results without needing to project into an anonymous type.