2013-08-23 45 views
-4

說明:我有一個包含datetime lasthello和string isconnect等其他客戶端對象的列表。 我現在已經將對象移動到一個sql表格而不是運行時列表。 我的問題,我將如何去通過表尋找以下目前的條目,並改變它。 - 以相當優化的方式(通過優化,我的意思是快) 「保持」也位於表格中,而不是在設置文件中。而isconnect現在是一個布爾,而不是一個字符串。轉換爲sql查詢

foreach(entry in mylist) 
{ 
    if ((DateTime.Now - TimeSpan.FromSeconds(Settings.Default.Hold)) > entry.lasthello && 
            entry.isConnect != "Disconnected") 
           { 
            entry.client.Disconnect(); 
           } 
} 

我如何計算sql查詢內的時間跨度?是否應該在多個查詢中完成?

解決!

using (SqlConnection conn = new SqlConnection(Connectionstring)) 
       { 

        SqlCommand cmd = new SqlCommand(DisconnectOnNoHello, conn); 
        cmd.Parameters.AddWithValue("@lasthello",(DateTime.Now - TimeSpan.FromSeconds(Convert.ToDouble(hold)))); 
        try 
        { 
         IScsServerClient client = (IScsServerClient)ByteArrayToObject((byte[]) cmd.ExecuteScalar());  
         client.Disconnect(); 
         closeConnection(conn); 
        } 
        catch (Exception ex) 
        { 
         EventLog.WriteEntry(ex.ToString()); 
        } 
       } 
+0

信息太少。你的桌子是怎麼樣的,你使用的是什麼rdbms? –

+0

這似乎應該留在內存中 - 如果您的服務器重新啓動,會話將被斷開。不要將其移至SQL。 – neeKo

+0

也許嘗試Linq到SQL?沒有太多的信息在你的問題。 – TheKingDave

回答

4

好,DateTime.Now - TimeSpan.FromSeconds(Settings.Default.Hold)似乎並不依賴於entry,所以你可以只計算出第一和把它作爲一個參數,即

select * 
from [SomeTable] 
where @foo > lasthello 
and isConnect <> 'Disconnected' 

但除此之外:datediff

+0

ofcourse我可以。非常感謝你! 不能相信我沒有看到它在開始>< – VisualBean

+0

所以沿着 行SELECT * FROM entrytable WHERE lasthello <@lasthellodiff and isconnect ='true' – VisualBean