Doubt with GetDate ()?

4

I'm having an SQL query that should bring me only the records whose date is greater than the date of the day, plus is coming records with the current date. Thanks!

   --não deveria mostrar a data de hoje
 select a.datavencimento  from TB_RECEBIMENTO a   
 left outer join   tb_plano_contas b  on  a.controleplano = b.controleplano               
 left outer join   tb_cliente_fornecedor d   on  a.controlecliente = d.controlecliente    
  where getdate() > a.datavencimento                                                 
     and a.statusregistro   = 'A' 
     and  b.tipododocumento = 'C' 
     and  a.controleempresa = '1' 
     order by a.datavencimento asc

Result:

2015-04-27 00:00:00.000
2015-04-27 00:00:00.000
2015-04-27 00:00:00.000
2015-04-28 00:00:00.000
2015-04-28 00:00:00.000
2015-04-28 00:00:00.000
2015-04-28 00:00:00.000
2015-04-28 00:00:00.000
    
asked by anonymous 28.04.2015 / 22:35

3 answers

1

The reason why this is happening is that GetDate() returns a DateTime , in addition to the date it also returns the Time part for hours, minutes, and seconds.

The recorded data is all with the% share from% to zero . When the comparison is made all dates today are less than getData ().

I hope you have made me understand.

    
28.04.2015 / 22:46
2

You should disregard the hours to make this comparison. So:

DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

One tip is to create a function for this, to make the code clearer:

CREATE FUNCTION truncate_date (@data DATETIME)
RETURNS DATETIME
AS
BEGIN
  RETURN 
(
    DATEADD(dd, 0, DATEDIFF(dd, 0, @data))
)
END

Then your Query would look like:

select a.datavencimento  from TB_RECEBIMENTO a   
left outer join   tb_plano_contas b  on  a.controleplano = b.controleplano               
left outer join   tb_cliente_fornecedor d   on  a.controlecliente = d.controlecliente    
where dbo.truncate_date(getdate()) > a.datavencimento
-- ou DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) > a.datavencimento
 and a.statusregistro   = 'A' 
 and  b.tipododocumento = 'C' 
 and  a.controleempresa = '1' 
 order by a.datavencimento asc
    
28.04.2015 / 23:00
1

You're getting this result because the current time (caught by GETDATE() ) is being considered (it's a DATETIME value). So today at noon today is higher than today at midnight (which seems to be the time of all maturities), and today's maturities meet the query condition. One of the possible workarounds is to convert the return from GETDATE to type DATE (available from SQL Server 2008):

WHERE CONVERT(DATE, GETDATE()) > a.datavencimento        
-- etc.
    
28.04.2015 / 22:48