Varchar operation in SQL 2014

Asked

Viewed 41 times

1

I am trying to do a less sql account in sql Sever management but this format error. I am wanting to do the months account 202103 - 202101 = 2 months

How to solve this format problem?

select *
    ,DPD = datediff(day, Dt_Atraso, Dt_Ref)
    ,DIAS_Prazo = datediff(day, Dt_Abertura, Dt_Vencimento)
    **,DIFERENCA = (MES_ATUAL - MES_ATRASO)**
from #chuv_pJ 

ERROR:

Msg 402, Level 16, State 1, Line 4
The data types varchar and varchar are incompatible in the subtract operator.
  • datediff(day, Dt_Abertura, Dt_Vencimento) if you want the difference in months, change the day for month

2 answers

2


The problem is that it is trying to subtract two varchar-like fields. It will be necessary to make a cast before. That cast will consider the value as date in order to be able to perform the calculation between dates. Before performing the cast, I suggest concatenating with the string +'01' to generate a valid date as per functional example below:

    select *
        ,DPD = datediff(day, Dt_Atraso, Dt_Ref)
        ,DIAS_Prazo = datediff(day, Dt_Abertura, Dt_Vencimento)
        ,DIFERENCA = DATEDIFF(MONTH,cast(MES_ATRASO+'01' as date),cast(MES_ATUAL+'01' as date))
    from #chuv_pJ 

0

As suggested in comment, to have the difference between two dates in months, you just need to change the "datepart", which is the first function parameter datediff().

SELECT *,
    DPD = datediff(day, Dt_Atraso, Dt_Ref),
    DIAS_Prazo = datediff(day, Dt_Abertura, Dt_Vencimento),
    DIFERENCA = datediff(month, Dt_Abertura, Dt_Vencimento)
FROM #chuv_pJ 
  • The problem is that the variable MES_ATUAL and MES_ATRASO is not in date format, it was date and was transformed into text, when I try to use the datiff the following error appears: Msg 241, Level 16, State 1, Line 1 Conversion failed when Converting date and/or time from Character string. I can turn this variable back into date?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.