If no where condition SQL Server

3

I have a Stored Procedure where I need to do a check for a date filter, if the start date is null I have to do in WHERE to get all records smaller than the end date, otherwise I make BETWEEN between dates.

Example

If the start date is null then:

select * from tabela where campoTabela <= @datafim

Otherwise:

select * from tabela where data between @dataInicial and @datafim
    
asked by anonymous 15.11.2018 / 12:26

4 answers

2

As a stored procedure one must be careful to avoid parameter sniffing .

If there is an index for the data column, this is a suggestion:

-- código #1
-- gera variáveis internas de limite
declare @xDataInicial date, @xDataFinal date;

IF @datainicial is not null
  set @xDataInicial= @datainicial
else
  set @xDataInicial= (SELECT top (1) data from tabela order by data);
set @xDataFinal= @datafim;

--
SELECT colunas
  from tabela
  where data between @xDataInicial and @xDataFinal;

In the above code the variables @x InitialD and @xDataFinal must be declared of the same data type of column data .

    
15.11.2018 / 20:20
0

If the goal is to execute everything in just one query, you can do it as follows:

SELECT  * 
FROM    tabela 
WHERE   (@dataInicial IS NULL       AND campoTabela <= @datafim)
    OR  (@dataInicial IS NOT NULL   AND data BETWEEN @dataInicial AND @datafim)

By putting OR you can have both conditions in the WHERE clause.

    
15.11.2018 / 12:42
0

You can do this:

if (@dataInicial is null)
begin

    select * from tabela where campoTabela <= @datafim

end
else
begin

    select * from tabela where data between @dataInicial and @datafim

end

You check if the parameter is null and according to this makes your select!

Below is a demonstration. When it is null , the displayed text is NULL, and when it is not it is NOT NOT NULL.

NOT NULL

NULL

    
15.11.2018 / 12:38
0

You can do this as follows

SELECT *
FROM tabela
WHERE (Data >= @dataInicial AND Data <= @datafim) 
       OR 
      (@dataInicial IS NULL AND Data <= @datafim);
    
15.11.2018 / 21:53