我想寫一個SQL(服務器)查詢將返回當天的所有事件,併爲所有事件列recurring
= 1,我希望它在當天返回此事件正在舉行,並在事件發生後的52周內舉行。作爲跟隨複雜的SQL服務器查詢
我的表結構:
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)
}
我迄今如下代碼:
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
);
這導致當存儲在該事件之日起查詢中數據庫,這個事件和52周的事件被返回。當人們在這一週之後的一個星期查詢事件時,什麼都不會返回。
可能存在[存在從對象類型WebMatrix.Data.DynamicRecord到已知託管提供程序本機類型的映射]的副本(http://stackoverflow.com/questions/9665051/no-mapping-exists-from-object-type -webmatrix-data-dynamicrecord-a-known-manag) – 2012-03-12 20:42:16
你的其他問題的答案指出你錯誤的方向......它與你的SQL無關 - 相反,你試圖通過在'groupID',這是一個'DynamicRecord','db.Query'。您需要從先前的結果集中獲取值,並將其轉換爲int。或者,我建議重新編寫這段代碼,因爲我沒有看到爲什麼你會使用'foreach'而不是在你的主查詢中進行額外的連接... – 2012-03-12 20:45:03
@MichaelFredrickson,謝謝你的迴應。我試圖做到這一點,但正如你可以告訴我,作爲初學者與SQL Server和C#掙扎。您是否介意提出我可以使用您建議的連接編寫的替代查詢,因爲我幾乎沒有編寫這樣一段代碼所需的技能? – 2012-03-12 20:53:31