Octavio, the error message indicates line 27 but in the code you transcribed there are 14 lines...
If column V.DATA is declared as datetime, it seems to me that the cause is related to the session LANGUAGE. One solution, which works independently of how LANGUAGE and/or DATEFORMAT is configured, is to use the Convert() function. It cannot be the Cast() function because it is context sensitive.
And, to facilitate code maintenance, I suggest you create variables to store the values of the period to be consulted.
-- código #1
declare @DataInicial datetime, @DataFinal datetime;
-- informe aqui as datas limite, no formato dd/mm/aaaa
set @DataInicial= Convert(datetime, '1/4/2016', 103);
set @DataFinal= Convert(datetime, '30/9/2016', 103);
--
SELECT
ROW_NUMBER() OVER(ORDER BY V.DATA ASC) AS ID,
V.CHAPA AS CHAPA,
F.NOME AS NOME,
V.DATA AS DATA,
CASE WHEN V.BATIDA IS NULL THEN 0 ELSE V.BATIDA END AS FOLGA
FROM
ARELBATIDATRANSITOVIEW AS V
LEFT JOIN V_DADOSFUNC AS F ON V.CHAPA = F.CHAPA
WHERE
V.CHAPA = 123
AND V.DATA BETWEEN @DataInicial and @DataFinal
GROUP BY V.CHAPA,V.DATA,F.NOME,V.BATIDA;
Code #1 used the 103 style in the Convert() function, which means that the date is given in the dd/mm/yyyy format. This makes it easier to maintain the code, as it is our day-to-day format. Since the variables @Initial and @Datafinal are declared as datetime, comparisons are all performed as values datetime.
There are factors that can confuse when manipulating dates in SQL Server, leading to errors in execution almost always related to the ignorance of how SQL Server interprets literals (strings) containing date.
For example, "2020-02-29 18:12:58" is correctly recognized as 29/2/2020 18:12:58 if the data type is datetime2 but can generate error message 242 if the data type is datetime and dateformat is not set to ymd. In the article Dominating dates and times in SQL Server this subject is dealt with in depth.
What type is your Data Field?
– Marconi
Line 27 is the line
AND V.DATA BETWEEN '2016-04-01 00:00:00.000' AND '2016-09-30 00:00:00.000'
?– Ricardo Pontual
@Ricardopontual Yes
– Chefe Druida
@Marconi V.Data
– Chefe Druida
Try a universal format that will work, like '20160401' or '20160401 00:00:00'
– Ricardo Pontual
This error can also be when you put a date that does not exist, like putting day 31 in months with 30 days.
– Andreia Nunes
About this error message I suggest reading the article Dominating dates and times in SQL Server: https://portosql.wordpress.com/2020/02/29/dominando-datas-horas/
– José Diz