第一,所以我沒必要重複複雜的表達式(該子查詢,要準確)不止一次我會重建你的腳本。
如果可能的話,使用SELECT而不是SET,像這樣:
SELECT @diffNSVY = CASE
WHEN rn.NSV < 0 THEN 0
ELSE (descrn.NSV - rn.NSV) * 1.0/rn.NSV /* extra '()' are removed as unneeded */
FROM
(select top 1 NSV from #temp where rn = 1) AS rn,
(select top 1 NSV from #temp where descrn = 1) AS descrn
接下來,問問自己,結果應該是什麼在分裂的情況下,通過零。它是否應該爲零?然後下一個優化步驟是簡單:
SELECT @diffNSVY = CASE
WHEN rn.NSV <= 0 THEN 0 /* changed '<' to '<=' to account for division by zero */
ELSE (descrn.NSV - rn.NSV) * 1.0/rn.NSV
FROM
(select top 1 NSV from #temp where rn = 1) AS rn,
(select top 1 NSV from #temp where descrn = 1) AS descrn
但是如果你希望結果是不確定的(NULL),所以你以後再處理它,這裏是你如何能做到這一點:
SELECT @diffNSVY = CASE
WHEN rn.NSV < 0 THEN 0
ELSE (descrn.NSV - rn.NSV) * 1.0/CASE rn.NSV WHEN 0 THEN NULL ELSE rn.NSV END
FROM
(select top 1 NSV from #temp where rn = 1) AS rn,
(select top 1 NSV from #temp where descrn = 1) AS descrn
一般,當我需要確保自己不會受到零分錯誤時,我發現這種模式很有用。我經常用這樣的:
...ISNULL(some_expression/CASE @Value WHEN 0 THEN NULL ELSE @Value END, 0)...
有時我使用它,而ISNULL
在這種情況下,我處理可能的空結果後使用一些更復雜的邏輯。
編輯:哦,還有一兩件事:用SELECT您可以一次有幾個任務,像這樣:
SELECT
@Var1 = expression1,
@Var2 = expression2,
...
難道這可能會幫助您簡化您的查詢呢?
你可以發送示例try --- catch實現上述查詢嗎? – sriramjitendra 2011-02-02 06:35:58