2013-11-15 58 views
1

我正在處理項目資源的每月小時數,並且我有一個要求,即每個資源記錄不能有負小時數。 (別問)SQL - 檢查負數的字段值並在負數時更改值

我正在創建一個存儲過程(SQL Server)來檢查每個月的小時數以查看記錄是否有一個或多個負值。如果記錄有一個或多個負值,則必須使用剩​​餘的每月值來抵消負值。

參考鏈接:SQL Fiddle

這個例子紀錄,爲3個月,它具有-48小時。我需要使用第一個月和第二個月(每個月都有24小時)來抵消第3個月的-48小時。因此第1到第3個月將是0,因爲第1個月和第2個月的總小時數將是+48,這將會否定第3個月的負小時數。

只需注:負數可能在任何月份,抵消負數的小時數可能來自一個或多個月。目標是消除負面小時數。如果沒有足夠的時間來抵消負數,則每個月的小時數將設置爲0.

在此先感謝!

+0

在這種情況下,我可能會使用CLR函數並在.NET中執行繁重的工作。雖然你可以在存儲過程中做到這一點,但它需要很多代碼,我可能會使用遊標,樞軸和case語句,而不是SQL查詢最擅長的。 – XN16

回答

0

我認爲下面是你想要的,或者至少可以讓你接近:

SELECT 
    CASE WHEN FCST_HR1 < 0 THEN 0 ELSE FCST_HR1 END AS FCST_HR1, 
    CASE WHEN FCST_HR2 < 0 THEN 0 ELSE FCST_HR2 END AS FCST_HR2, 
    CASE WHEN FCST_HR3 < 0 THEN 0 ELSE FCST_HR3 END AS FCST_HR3, 
    CASE WHEN FCST_HR4 < 0 THEN 0 ELSE FCST_HR4 END AS FCST_HR4, 
    CASE WHEN FCST_HR5 < 0 THEN 0 ELSE FCST_HR5 END AS FCST_HR5, 
    CASE WHEN FCST_HR6 < 0 THEN 0 ELSE FCST_HR6 END AS FCST_HR6, 
    CASE WHEN FCST_HR7 < 0 THEN 0 ELSE FCST_HR7 END AS FCST_HR7, 
    CASE WHEN FCST_HR8 < 0 THEN 0 ELSE FCST_HR8 END AS FCST_HR8, 
    CASE WHEN FCST_HR9 < 0 THEN 0 ELSE FCST_HR9 END AS FCST_HR9, 
    CASE WHEN FCST_HR10 < 0 THEN 0 ELSE FCST_HR10 END AS FCST_HR10, 
    CASE WHEN FCST_HR11 < 0 THEN 0 ELSE FCST_HR11 END AS FCST_HR11, 
    CASE WHEN FCST_HR12 < 0 THEN 0 ELSE FCST_HR12 END AS FCST_HR12 
FROM 
(select 
    FCST_HR1, 
    FCST_HR1 + FCST_HR2 AS FCST_HR2, 
    FCST_HR1 + FCST_HR2 + FCST_HR3 AS FCST_HR3, 
    FCST_HR1 + FCST_HR2 + FCST_HR3 + FCST_HR4 AS FCST_HR4, 
    FCST_HR1 + FCST_HR2 + FCST_HR3 + FCST_HR4 + FCST_HR5 AS FCST_HR5, 
    FCST_HR1 + FCST_HR2 + FCST_HR3 + FCST_HR4 + FCST_HR5 + FCST_HR6 AS FCST_HR6, 
    FCST_HR1 + FCST_HR2 + FCST_HR3 + FCST_HR4 + FCST_HR5 + FCST_HR6 
    + FCST_HR7 AS FCST_HR7, 
    FCST_HR1 + FCST_HR2 + FCST_HR3 + FCST_HR4 + FCST_HR5 + FCST_HR6 
    + FCST_HR7 + FCST_HR8 AS FCST_HR8, 
    FCST_HR1 + FCST_HR2 + FCST_HR3 + FCST_HR4 + FCST_HR5 + FCST_HR6 
    + FCST_HR7 + FCST_HR8 + FCST_HR9 AS FCST_HR9, 
    FCST_HR1 + FCST_HR2 + FCST_HR3 + FCST_HR4 + FCST_HR5 + FCST_HR6 
    + FCST_HR7 + FCST_HR8 + FCST_HR9 + FCST_HR10 AS FCST_HR10, 
    FCST_HR1 + FCST_HR2 + FCST_HR3 + FCST_HR4 + FCST_HR5 + FCST_HR6 
    + FCST_HR7 + FCST_HR8 + FCST_HR9 + FCST_HR10 + FCST_HR11 AS FCST_HR11, 
    FCST_HR1 + FCST_HR2 + FCST_HR3 + FCST_HR4 + FCST_HR5 + FCST_HR6 
    + FCST_HR7 + FCST_HR8 + FCST_HR9 + FCST_HR10 + FCST_HR11 + FCST_HR12 AS FCST_HR12 
from RSRC_HR 
where rsrc_id = '2045831579F511750') t 

一點很難理解你想要什麼,但它似乎是跨列總運行?