我正在使用c#,sqlce,datatable。我選擇帶有此查詢的產品:在DataTable中過濾結果(date1和date2之間的日期列)
select price from products where productid=myproduct and mydate between startdate and finaldate and clientid=myclient
但是這需要花費很多時間。 所以我可以用一個數據表來存儲產品:
datatable prices = new datatable();
prices=this.returntable("select productid,startdate,finaldate,client from products")
for(int i=0;i<allproductsihave;i++) {
product.newprice=this.getmyprice(prices,product.client,product.id,product.date);
}
private decimal getmyprice(datatable products,string myclient, string myproduct, datetime mydate)
{
//how do I do at here the equivalent to first sql query?
//for select a product from a datatable where my date is between 2 dates,
//and client=myclient and productid=myproduct
return Convert.Todecimal(datatable.prices[something]["price"].tostring());
}
這樣,我不應該連接到數據庫,對每個產品的查詢。 它是否可行?
也許在做convert.todatetime startdate和finaldate?
爲什麼查詢需要很長時間?在productid,clientid,startdate上創建一個索引。無論你在C#中做什麼都不會更快,是嗎? – pilotcam
以及我的老闆不需要查詢,他想要的就像我所描述的 –
你的老闆不是程序員是他嗎?在代碼中執行此操作無法擴展,因爲您正在將整個表加載到內存中。這會導致大量不必要的網絡流量和不必要的內存消耗。另外,通過for循環迭代意味着每個元素都必須迭代,而不管它是否符合條件。除此之外,您正在使用(可能是無類型的)DataTable,並且您測試的每個元素都將導致拆箱操作。這是一個巨大的時間浪費。讓數據庫完成設計的目的會更好。 – JamieSee