2013-08-23 44 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