SQL查询日期时间问题

时间:2017-05-02 15:52:16

标签: sql-server

我在SQL Server上查询了基于日期时间条件的错误结果。

SET LANGUAGE Português

select distinct
       CONVERT(varchar(10), DATENAME(MONTH, i9_parcelaBase.i9_data_vencimento)) + '/' + CONVERT(varchar(10), 
       DATENAME(YEAR,i9_parcelaBase.i9_data_vencimento)) AS Periodo,
       i9_parcelaBase.i9_data_vencimento,
       i9_parcelaBase.i9_data_limite_envio_nf,
       i9_parcelaBase.i9_status_atual,
       i9_processo_statusBase.i9_status, 
       i9_processo_statusBase.i9_name
      --i9_nota_fiscalBase.i9_nota_fiscalid as ID
from  i9_parcelaBase 
  left join i9_processo_statusBase 
    on i9_parcelaBase.i9_status_atual = i9_processo_statusBase.i9_processo_statusId
where  i9_processo_statusBase.i9_entidade = 100000002 
and    i9_parcelaBase.i9_data_vencimento between CONVERT(varchar(10),  year(getdate())-1) + '-' +  CONVERT(varchar(10),  month(getdate())+1) + '-1'   
                                             and CONVERT(varchar(10),  year(getdate())) + '-' +  CONVERT(varchar(10),  month(getdate())) + '-1'
order by i9_data_vencimento asc

基本上,没有' 0'之前(必要时)。

样品: 实际回报:' 2017-6-1' 预期回报' 2017-06-01'

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

根据您的查询,i9_data_vencimento预计仅以-1结束,而不是-01。您可以将字符串转换为日期,然后将其重新转换为字符串作为格式化的方式:

select distinct
       CONVERT(varchar(10), DATENAME(MONTH, i9_parcelaBase.i9_data_vencimento)) + '/' + CONVERT(varchar(10), 
       DATENAME(YEAR,i9_parcelaBase.i9_data_vencimento)) AS Periodo,
       CONVERT( VARCHAR(10), CONVERT( DATETIME, i9_parcelaBase.i9_data_vencimento ), 120 ) AS i9_data_vencimento,
        :
        :

另外,考虑到i9_data_vencimento只是一个字符串,并且假设它总是以'yyyy-mm-1'格式的'1'结尾,你可以使用LEFT函数去除最后一个字符并将其替换为' 01' :

SELECT DISTINCT
       :
       LEFT(i9_parcelaBase.i9_data_vencimento, 8) + '01' AS i9_data_vencimento,
       :