我的任務是編寫一個允許用戶搜索價格表的應用程序,其中價格在3個不同的鍵上唯一,例如狀態,出版商,和型(可能有任何數量的與任何3個字段的相同的密鑰值的行,但僅存在一個行與狀態 =「俄亥俄」,出版商 =」 Bob',並且類型 ='硅')。當用戶選擇狀態和出版商,他們提出的所有類型與狀態和出版商的列表。我運行一個存儲過程來提取這些項目,並且我拉取最近的價格,但是我也需要拉第二個最近的價格,並進行數學計算,以便將價格變化顯示給用戶。目前,我創建了以下函數,但是它會使我的存儲過程減慢1到40秒,具體取決於服務器在執行時的心情。獲取T-SQL中所有最新價格的價格變化
BEGIN
-- Declare the return variable here
DECLARE @priceChange float
DECLARE @currentPriceDate date
DECLARE @currentPrice float
DECLARE @previousPrice float
-- Add the T-SQL statements to compute the return value here
SELECT TOP 1 @currentPriceDate=PriceDate ,@CurrentPrice=MarketPrice
FROM MarketPrice_Table
LEFT JOIN PriceEffectiveDate_Table ON MarketPrice_Table.PriceDate = PriceEffectiveDate_Table.EffectiveDate
AND MarketPrice_Table.PublisherID = PriceEffectiveDate_Table.PublisherID
WHERE TypeID = @TypeID
AND MarketPrice_Table.PublisherID = @PublisherID
AND MarketPrice_Table.StateID = @StateID
ORDER BY PriceDate DESC;
SET @previousPrice = (SELECT TOP 1 MarketPrice
FROM MarketPrice_Table
LEFT JOIN PriceEffectiveDate_Table ON MarketPrice_Table.PriceDate = PriceEffectiveDate_Table.EffectiveDate
AND MarketPrice_Table.PublisherID = PriceEffectiveDate_Table.PublisherID
WHERE TypeID = @TypeID
AND MarketPrice_Table.PublisherID = @PublisherID
AND MarketPrice_Table.StateID = @StateID
AND MarketPrice_Table.PriceDate <> @currentPriceDate
ORDER BY PriceDate DESC);
SET @priceChange = @currentPrice - @previousPrice;
-- Return the result of the function
RETURN @priceChange
END
是否有更有效的方法來做到這一點,所以我不在存儲過程中每行兩個查詢?
非常感謝您的幫助,如果我能進一步澄清,請告訴我!
首先,我建議你轉換日期字符串轉換(VARCHAR,MarketPrice_Table.PriceDate,112)<>轉換(VARCHAR,@ currentPriceDate,112) – MelgoV 2014-08-29 19:14:23