如果我想更新我的记录,如果某个条件是真的,我该怎么用

时间:2018-02-15 22:58:30

标签: sql-server if-statement sql-server-2012

我想更新我的记录,如果客户的最后一次付款当天大于100;

 update clients set ind_mo = 2,
ind_pay=2

如果小于100;

update clients set ind_mo = 1, 
ind_pay = 1

如果客户自己的= 0

update clients set ind_mo = 1,
ind_pay = 1 

我已经尝试了这个但是如果它自己的0

它不会更新我的记录
if (datediff(day,((select top 1 fec_ven from 
cxc_cuedoc  cue inner join cxc_cliente cli
on cli.cod_cli = cue.cod_cli  where sal_doc !=0 and cue.tip_doc = '010'  and num_doc=cue.num_doc)),getdate())) > 110
update cxc_cliente
 set ind_mora ='2',
IND_JURIDICO = '2';
else
update cxc_cliente
set ind_mora = '1',
ind_juridico ='1'

1 个答案:

答案 0 :(得分:0)

UPDATE Cli
 SET  Cli.ind_mo  = CASE WHEN DATEDIFF(DAY , fec_ven , GETDATE()) > 100 
                         THEN 2 ELSE 1 END
     ,Cli.ind_pay = CASE WHEN DATEDIFF(DAY , fec_ven , GETDATE()) > 100 
                         THEN 2 ELSE 1 END
from cxc_cuedoc  cue 
inner join cxc_cliente cli on cli.cod_cli = cue.cod_cli  
                          and cli.num_doc = cue.num_doc
where sal_doc != 0 
and cue.tip_doc = '010'  

或者如果你只对最后一行感兴趣,可能是这样的......

WITH X AS (
SELECT ind_mo , ind_pay , fec_ven 
     , ROW_NUMBER() OVER (PARTITION BY cli.cod_cli ORDER BY fec_ven DESC) rn 
FROM cxc_cuedoc  cue 
inner join cxc_cliente cli on cli.cod_cli = cue.cod_cli  
                          and cli.num_doc = cue.num_doc
where sal_doc !=0 
and cue.tip_doc = '010'
)
UPDATE x
  SET  x.ind_mo  = CASE WHEN DATEDIFF(DAY , x.fec_ven , GETDATE()) > 100 
                         THEN 2 ELSE 1 END
     ,x.ind_pay = CASE WHEN DATEDIFF(DAY , x.fec_ven , GETDATE()) > 100 
                         THEN 2 ELSE 1 END 
WHERE x.rn = 1