SQL - 检查负数的字段值,如果为负则更改值

时间:2013-11-15 19:43:31

标签: sql sql-server stored-procedures

我正在处理项目资源的每月工作时间,并且我要求每个资源记录不能有负数小时。 (不要问)

我希望创建一个存储过程(SQL Server)来检查每个月的小时数,以查看记录是否有一个或多个负值。如果记录有一个或多个负值,我必须使用剩​​余的月度值来抵消负数。

请参阅链接:SQL Fiddle

此示例记录,对于第3个月,它有-48小时。我需要使用每月24小时的第1和第2个月来抵消第3个月的-48小时。因此第1个月到第3个月将是0,因为第1个月和第2个月的总小时数将是+48,这将是否定第3个月的负面时间。

请注意:负数可以在任何一个月内,负数的抵消时间可能来自一个月或多个月。目标是消除负面时间。如果没有足够的时间来抵消负数,则每个月的小时数将设置为0。

提前致谢!!!

1 个答案:

答案 0 :(得分: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

有点难以准确理解你想要什么,但它似乎是一个跨列的运行总计?