简体   繁体   English

SQL查询日期时间问题

[英]SQL Query datetime issue

I have a query on SQL Server that's finding wrong results based on a datetime condition. 我在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

Basically, Month that's receiving data without '0' before (when necessary). 基本上,月份之前(必要时)接收的数据不包含“ 0”。

Sample: Actual return: '2017-6-1' Expected return '2017-06-01' 示例:实际回报率:“ 2017-6-1”预期回报率:“ 2017-06-01”

Can anyone help me to solve this problem? 谁能帮我解决这个问题?

By the look of your query, i9_data_vencimento is expected to end with just -1, not -01. 从查询的角度来看,i9_data_vencimento的结尾应该是-1,而不是-01。 You can cast the string into a date, then recast it back as a string as a way to format it: 您可以将字符串转换为日期,然后将其重铸为字符串,以设置其格式:

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,
        :
        :

Also, considering that i9_data_vencimento is just a string, and assuming it always ends with '1' in the format 'yyyy-mm-1', you could use a LEFT function to strip off the last character and replace it with '01': 另外,考虑到i9_data_vencimento只是一个字符串,并假设它始终以'yyyy-mm-1'格式以'1'结尾,则可以使用LEFT函数剥离最后一个字符并将其替换为'01':

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM