如果变量有数据,则SQL将条件添加到where子句

时间:2017-11-09 16:26:39

标签: sql-server tsql

我在我的SQL脚本顶部设置变量的日期,然后在许多其他地方调用这些变量以保持简单。

我想添加一个条件where子句来添加一个AND语句,但只有在@test_patient字段中有数据时才会这样。

declare @from_date date
set @from_date = '2017-01-01 00:00:01'

declare @to_date date
set @to_date = '2017-12-31 00:00:01'  

declare @test_patients NVARCHAR(MAX)
set @test_patients = ('123','234') 

select * from table
where 
    date between @from_date and @to_date
    AND other things
    AND other things...

......这是我需要帮助的部分......

    IF @test_patients IS NOT NULL 
        Add this->  and p.PatientId in @test_patients               
    ELSE nothing... move along...

基本上,代码会抓住所有患者,除非我特意加入一些我希望它找到的测试患者。如果我不在我的变量中填充任何测试患者,我不希望它寻找特定患者。

3 个答案:

答案 0 :(得分:1)

你可以这样做

select * from table
where 
    date between @from_date and @to_date
    AND other things
    AND other things... 
    AND (@test_patients IS NULL OR (@test_patients IS NOT NULL AND p.PatientId in @test_patients    ))
    AND (@test_patients IS NULL OR (@test_patients IS NOT NULL AND otherthing....    ))

答案 1 :(得分:0)

你可以这样做:

WHERE p.PatientId in @test_patients OR @test_patients IS NULL

答案 2 :(得分:0)

您可以使用OR

select * from table
where 
    date between @from_date and @to_date
    AND other things
    AND other things...
    AND (@test_patients IS NULL OR p.PatientID = @test_patients)