3

I am currently trying to do a Select in my SQL Server database using a parameter with Datetime type. But I need this parameter only has the format YYYY-MM-DD date because of the following query in SQL I'm using and it's working :

select 
    idCliente, DescCliente, DescAnalista , StatusChamado , DataAtendimento 
from 
    Atendimento 
where 
    cast ([DataAtendimento] as date) = '2016-04-27';

I read several posts indicating that I use DbType or .ToString but when running it is generating error alleging failure to convert the string to the date / time format.

This is how I use the SqlParameter:

DateTime date;
date = Data;

try
{
    sqlClient.Command.Parameters.AddWithValue("@adate", date);
    sqlClient.Command.CommandText = @" select idCliente, DescCliente, DescAnalista , StatusChamado , DataAtendimento from Atendimento where cast ([DataAtendimento] as date) = '@adate';";

I need a help from you guys , I'm not finding any means that can perform this select

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

5

You have to remove the '' in = '@adate'. With the '' in place, it effectively turns your query into:

select 
    idCliente, DescCliente, DescAnalista , StatusChamado , DataAtendimento 
from Atendimento 
where cast ([DataAtendimento] as date) = '@date';

This means that cast([DateAtendimento] as date) is compared against the string '@date', thus the conversion to date error.

Felix Pamittan
  • 31,544
  • 7
  • 41
  • 67
  • That was exactly what was happening, I do not think I was hours researching and trying to convert the date thinking that the problem was it , thank you for help – André Freindorfer Apr 28 '16 at 02:41