如何在cluase中插入IF? (TSQL)

时间:2017-08-09 08:44:21

标签: tsql

我在TSQL中有这个查询

DECLARE @DATA_INIZIO AS DATE
DECLARE @DATA_FINE AS DATE    
SELECT 'TEMPERATURA RILEVATA', VS.EffectiveTimeMin as ORA, CAST(VS.Value AS INT), row_number() over (order by VS.EffectiveTimeMin) AS CONTEGGIO
        FROM AA_V_PHR_CCD_VitalSigns V INNER JOIN AA_V_PHR_CCD_VitalSignsXResults VS ON V.ID = VS.IDVitalSigns
        WHERE V.IDResultTypeValueSet = 23 AND V.IDClinicalDocument = 46
        ORDER BY VS.EffectiveTimeMin asc

但是,我想在where子句中添加这个条件:

IF(@Data_Inizio is not null and @Data_Fine is not null)
   v.effectivetime between @data_inizio and @data_fine

我该怎么做?

2 个答案:

答案 0 :(得分:1)

(
    (@Data_Inizio is not null and @Data_Fine is not null) 
    AND 
    v.effectivetime between @data_inizio and @data_fine
)

如果我理解正确,应该没事。

嗯,也许您没有正确的值,或者您的日期不正确,请查看下面的示例:

DECLARE @DATA_INIZIO AS DATE = '2017/01/01'
DECLARE @DATA_FINE AS DATE = '2017/02/01'

Declare @Tmp Table 
(
    IdResult Int, IdClinical Int, EffectiveTime DateTime
)

Insert Into @Tmp (IdResult, IdClinical, EffectiveTime)
Values 
    (23, 46, '2017/01/23'), (22, 46, '2017/01/23'),
    (23, 46, '2017/01/2'), (23, 47, '2017/01/23'),
    (23, 46, '2017/01/5'), (23, 46, '2017/02/23')

SELECT *
FROM 
    @Tmp V
WHERE 
    V.IdResult = 23 AND V.IdClinical = 46
    AND
    (
        (@Data_Inizio is null OR @Data_Fine is null) 
        OR 
        v.effectivetime between @data_inizio and @data_fine
    )

答案 1 :(得分:1)

尝试在WHERE子句中添加这些行:

SELECT
    'TEMPERATURA RILEVATA',
    VS.EffectiveTimeMin as ORA,
    CAST(VS.Value AS INT),
    row_number() over (order by VS.EffectiveTimeMin) AS CONTEGGIO
FROM
    AA_V_PHR_CCD_VitalSigns V
    INNER JOIN AA_V_PHR_CCD_VitalSignsXResults VS
        ON V.ID = VS.IDVitalSigns
WHERE
    V.IDResultTypeValueSet = 23
    AND V.IDClinicalDocument = 46
    AND ( (@DATA_INIZIO is null OR @DATA_FINE is null)
        OR                                                -- when both are not null
        (@DATA_INIZIO <= v.effectivetime AND v.effectivetime <= @DATA_FINE)
        )
ORDER BY VS.EffectiveTimeMin ASC

您可以将您的IF语句“翻译”为:  当DATA_INIZIO或DATA_FINE未设置(null)时返回记录  当它们都被设置时 - 检查v.effectivetime是否适合它们的范围