转换为sql查询

时间:2013-08-23 12:20:51

标签: c# sql

说明:我有一个客户端对象列表,其中包含datetime lasthello和string isconnect等。 我现在已将对象移动到sql表而不是运行时列表。 我的问题是,我将如何在表格中查找存在以下内容的条目,并进行更改。 - 以相当优化的方式(通过优化我的意思是快速) “hold”现在也位于表格中,而不是设置文件中。而isconnect现在是一个bool,而不是一个字符串。

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());
                    }
                }

1 个答案:

答案 0 :(得分:4)

好吧,DateTime.Now - TimeSpan.FromSeconds(Settings.Default.Hold)似乎并不依赖于entry,所以你可以先计算它并将其作为参数传递,即

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

但除此之外:datediff